10 JavaScript concepts every Node.js programmer must master

Node.js owes much to JavaScript for its higher popularity. JavaScript is a multi-paradigm language. It supports many different styles of programming, including functional programming, procedural programming and object-oriented programming. It also allows the developer to be flexible and take advantage of the various programming styles. Hence it is necessary for Node.js programmer to be a master in some JavaScript concepts. Let’s see which are these concepts.

JavaScript concepts every Node.js programmer must master

1. JavaScript(ES6) Class-

JavaScript classes are introduced in ES6. These classes are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript. In early ES5 using function expression. 

Classes are special functions and you can define function expressions and function declarations. Class syntax has two components-

 1. Class expressions  

 2.Class declarations.

ES6 Class-

class Bike{

 constructor(color, model) {

   this.color= color;

   this.model= model;

 }

}

Benefits of using class-

  1. Convenient and self -contained syntax.
  2. A solitary, accepted approach to copy classes in JavaScript.
  3. More familiar to people those are using class-based language.

2. JavaScript Prototype-

When an object is created in JavaScript, JavaScript engine adds a _proto_property to the newly created object. This is called _proto_points to the prototype object of the constructor function.

function Car(model,color){

 this.model = model,

 this.color = color

}

Car.prototype.getDetails = function(){

return this.model+’ bike is ‘+this.color;

}

var carObj1 = new Car(‘BMW’,’Black’);

console.log(carObj1.getDetails());

The carObj1 object, which is created using the Car constructor function. It  has a __proto__ property which points to the prototype object of the constructor function Car. In below code, both carObj1 it’s __proto__ property and Car.prototype property is equal. Let’s check if they point at the same location using === operator.

console.log(carObj1.__proto__ === Car.prototype );//output : true

So using prototype property, how many objects are created functions are loaded into memory only once and we can override functions if required.

3. JavaScript Closure-

Closure is a combination of a function and the environment within which that function was declared.  It is an inner function that has access to the outer function’s variables – scope chain. Closure has three scope chains – 

  1. It has access to its own scope 
  2. Closure has access to the outer function’s variables
  3. It has access to the global variables 

Closure Example-

function User(name){  var displayName = function(greeting){

  console.log(greeting+’ ‘+name);

 }

return displayName;

}

var myFunc = User(‘Raj’);myFunc(‘Welcome ‘); //Output: Welcome Raj

myFunc(‘Hello ‘); //output: Hello Raj

In this code, the outer function User() returns an inner function as displayName(),The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

4. Module Pattern-

In JavaScript language, a module is referred as a small unit unit of independent and reusable code. Modules are the strong base for many JavaScript design patterns. These strong base are necessary for building any non-trivial JavaScript-based application. JavaScript module export as the value instead of define a type, as JavaScript module can export an object, Modules that export a string containing an HTML template or a CSS stylesheet are also common. JavaScript language don’t have private keyword. But we can achieve private methods and properties using closures.

var myModule = (function() {

   ‘use strict’;

   var _privateProperty = ‘Good Morning’;

   function _privateMethod() {

       console.log(_privateProperty);

   }

   return {

       publicMethod: function() {

           _privateMethod();

       }

   };

}());

myModule.publicMethod();                    // outputs ‘Good Morning’  

console.log(myModule._privateProperty);     // is undefined     

protected by the module closure

myModule._privateMethod();                  // is TypeError protected by the module closure

These modules can be exported to the other JS files using the export keyword,

//myMOdule.js file 

exportdefault myModule;

You can import module to another JS file.

//second.js file

import myModule from ‘./myModule’;

Use of Module-

  1. Namespacing
  2. Reusability
  3. Maintainability

5. Hoisting-

Hoisting is a JavaScript mechanism in which variables and function declarations are moved to the top of their scope before execution of code.

Simply, explanation for Hoisting with code,

         console.log(Hoist);

         var Hoist = ‘The variable Has been hoisted’;

         //output : undefined//

JavaScript has hoisted the variable declaration. Hence the code above looks like to the interpreter.

        var Hoist;

        console.log(Hoist);

        Hoist = ‘The variable Has been hoisted’;

JavaScript only hoists declarations, not initialization.

Definitely, this implies regardless of where functions and variables are declared. They are moved to the top of the scope regardless of whether their scope is global or local. Hence this also match for a variable of function level scope also hoisted.

Hoisting let-

  1. Var, const keyword in JavaScript (ES6)
  2. Hoisting classes
  3. Hoisting Functions

6. Scope-

Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code. According to this definition of scope, the point in limiting the visibility of variables and not having everything available everywhere in your code. Types of Scope-

  1. Global Scope
  2. Local Scope

var greeting=’Welcome to blog’;

(function(){

 console.log(greeting); //Output: Welcome to blog

})();

in the above code, greeting variable should be global scope, it can access inside the function,

(function(){

 var greeting = ‘Welcome to blog’;

 console.log(greeting); //Output: Welcome to blog

})();

console.log(greeting); //Output:Reference-Error greeting not defined

Consider the above code for local scope,

In scope level variables in JavaScript ES6 has updated hoisting variable let, var, const type check with that, In order to learn the scope, you need to understand hoisting also.

7. Currying-

Currying is a technique of evaluating a function with multiple arguments, into a sequence of function with a single argument. When a function takes the first arguments (instead of taking all arguments at one time) and return a new function that takes the second one and returns a new function which takes the third one, and so forth until all arguments have been fulfilled.

consider below example code:

var add =   function (a){

                return function(b){

                      return function(c){

                             return a+b+c;

                             }       

                       }

                 }

console.log(add(2)(3)(4)); //output 9

console.log(add(3)(4)(5)); //output 12

this currying achieving through closures. Hence the above program variables a,b private properties of the parent function.

Use of currying-

It helps to create a higher order function. It is extremely helpful in event handling.

8. Memorization-

It is a programming technique which attempts to increase a function’s performance by caching its previously computed results. Because JavaScript objects behave like associative arrays, they are ideal candidates to act as caches. When each time a memorized function is called, its parameters are used to index the cache. If the data is available, it will be returned without execution of complete function. If the data is not cached, the function is executed and the result is added to the cache. The function is an integral part of programming. They help for modularity and reusable to our code. As per above definition, memorization is an optimizing our code.

const memoizedAdd = () => {

 let cache = {};

return (value) => {

 if (value in cache) {

  console.log(‘Fetching from cache’);

  return cache[value];

 }

 else {

  console.log(‘Calculating result’);

  let result = value + 10;

  cache[value] = result;

  return result;

 }

}

}

// returned function from memoizedAdd

const newAdd = memoizedAdd();

console.log(newAdd(9)); //output: 19 calculated

console.log(newAdd(9)); //output: 19 cached

9. Callback Function-

Definition-

A reference to executable code, or a piece of executable code that is passed as an argument to other code. 

According to the above definition, the callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

function greeting(name) {

console.log(‘Hello ‘+name);

}

function processUserInput(callback) {

 //var name = prompt(‘Please enter your name.’);

 name=’William’;

 callback(name);

}

processUserInput(greeting); //output Hello William

In this program, function greeting passed as an argument to the processUserInput function

10. Polymorphism in JavaScript:

Polymorphism is one of the fundamentals of Object Oriented Programming(OOP). It allows the designing of objects to share behaviors and to be able to override shared behaviors with specific ones. Polymorphism takes advantage of inheritance in order to make this happen.

let’s look at the sample code for override a function in JavaScript

var employee = new Employee(‘William’);

//override function

//this method going to execute

Employee.prototype.getDetails = function(){

   return this.name.toUpperCase();

}

console.log(employee.getDetails());  //outPut: William

//object and prototype function

function Employee(name){

  this.name = name;

}

Employee.prototype.getDetails = function(){

  return this.name;

}

In the above program, prototype based method for an Employee constructor function has to override by another prototype function as return the Name as UpperCase. Hence, we can override a function in different Scope, and also possible for method overloading. JS doesn’t have method overloading native but still, we can achieve.

Are you looking for a web development to boost your business?Then you are at the right place. We at Solace believe in benefits and effectiveness of using Node in development. We have a team expert in javascript and node development, which will give you the best solution using new features of Node. To get a free quote for any software development using Node, contact us.