Javascript : Closures

Def: A closure is a function having access to the parent scope, even after the parent function has closed.

I know, its confusing to understand JS closures; I will try to explain below in as simple terms as I can;
Remember:

  • Aim  of “closures” is to create access to ‘private’ variables of a function, even after that function is closed.
  • Immediately Invoking function only runs once.

 

Steps to create closure: (Counter Function)

  1. Write a increment function which returns count = count +1;
    function(){ return count = count +1; }
  2. Write an anonymous function which returns above function; also initialize counter here;
    function (){var counter = 0;return function(){return count = count +1;}}
  3. Create an immediately invoking functiona. start with ()();
    b. Put above function into first braces;

    (function (){var counter = 0;return function(){return count = count +1;}})();

  4. Assign this immediately invoking function to a variable & Done.>!!! Here, the final code would look like;
    var add = (function () {var counter = 0;return function () {return counter += 1;}})();add();
    add();

    Result : 2


Let’s understand it now;

  1. As stated above, IIF only runs once; therefore counter gets initialized once; no matter how many times you call the function. Here the variable is ‘private‘, means it can only be changed by methods within that function.
  2. For the inner function; that variable is accessible & in the return statement its value gets incremented by 1, every time it gets called. Here, the variable becomes ‘protected’ & not accessible for outside world.Wonderful..!! isn’t it?