Closure in Javascript

 What is closure?

Closure means that an inner function always has access to the variables and parameters of its outer function, even after the outer function has returned.

Before moving forward you need to understands lexical environment in JavaScript.

Lexical Environment 


A lexical scope or static scope in JavaScript refers to the accessibility of the variables, functions, and objects based on their physical location in the source code.

Lexical in general means in hierarchy or in a sequence. Whenever a new execution context(EC) is created a new lexical environment  is created and it is referenced in local EC in memory space.

Lexical Environment: Local Memory + Lexical Environment of its Parent

So in short, a lexical environment is a place where variables and functions live or physically present during the program execution.

function outer(){

var n = 20;

  function inner(){

  console.log(n);

  }

inner();

}

outer();//print : 20

console.log(n);  //reference error

In the above script, function "inner" is lexically inside the function "outer", inner function can access their parent scope.

Closure


function outer(){
    var n = 20;
    return function inner(){
            console.log(n);
    }
}

var outerFunction = outer();
 outerFunction(); // print 20;
 console.log(n); // reference error

Above example is similar to the previous example, only difference is
"inner" function is returned before it's execution but still works as expected. 

As per the definition closure has access to lexical environment event after returned before it's execution.

Closure Function Scope

Every closure has three scopes : 
  1.  Local Scope
  2.  Outer Functions Scope
  3.  Global Scope
 
var n1 = 10;

function outer(n2){
    var n3 = 4;
        return function inner(n4){
            console.log(n1+n2+n3+n4);
        }
    
}
outer(10)(10); //print : 34

From above example , it is clear that closure has  access to local, outer function and global scope.

Performance consideration

It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.

Benefit of closure

Data encapsulation can be achieved using closure.

Hurray !!!








Comments