Tuesday, May 2, 2017

Closures in JavaScript


A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

Edit in plnkr

  • In Java script the variables that are defined outside the function are available inside, because JavaScript uses lexical scoping
  • Inner functions is also closure.
  • If the variable is not defined in the function, then it would keep looking outside the function
  • If it does not find the variable then it would be undefined.

Note:
1) Functions are also objects in JavaScript
2) We can create unlimited amount of functions using closures. It keeps the variable it needs to execute

var outside10;
var sum = function() {
 inner=20;
 return outside+inner;
}
console.log(sum());
//Here I am changing the value 
var outside=20;
console.log(sum());

var addTo =function(outer)
{
    var add=function(inner)
    {
        return outer+inner;
    }
    return add;
}

//pass value to outer function
var valThree=addTo(3);
var valFour=addTo(4);
//Here we are passing value to the inner variable
console.log(valThree(1));
console.log(valFour(1));

Output

C:\Development\NodeProjects\vanilanode>node closures
30
40
4
5

Note: Using chrome browser, We can see the closure value retained under scope


Closure value changed after second call



No comments:

Post a Comment