Understanding Javascript Closure

Closure is a nested function that has access to the variables in the outer (enclosing) function’s scope chain. It has access to variables in three scopes:

  • Variable in its own scope.
  • Variables in the enclosing (outer) function’s scope.
  • Global variables.

var globalVariable = 'Global variable.';

function outerFunction() {
  var outerFunctionVariable = 'Outer function variable.';
  
  function innerFunction () {
    var innerFunctionVariable = 'Inner function variable.';
    console.log("This is " + innerFunctionVariable);
    console.log("I can also access " + outerFunctionVariable);
    console.log("This is a " + globalVariable);
  };
  innerFunction();
};
outerFunction();

Best part of closure is that the nested (inner) function can access the variables from the outer scope even after the outer function has returned.

function myFunction(x) {
    var outerVariable = x;
    return function() {
        console.log(outerVariable);
    };
};

var secondFunction = myFunction("This is outer variable");
secondFunction();
Share

One thought on “Understanding Javascript Closure

Leave a Reply

Your email address will not be published. Required fields are marked *