Nov 29, 2016

Closures In Javascript

Actual understanding : Closure is a function that stays alive or connected to its parent Scope or parent function even after Parent scope or parent functions execution is over.


Problem : Suppose you are told to write a function that increments counter value by 1, What will you do ?


Obviously We would Code
var counter = 0;

function add() {
    return counter += 1;
}
add(); //Outputs 1
add(); //Outputs 2
add(); //Outputs 3



But this code is considered buggy as counter variable is directly accessible and any one can set value directly without using add() function

So To make above code bulletproof we  add closure function to it


Solution 1 :

var add = (function () { //outer function
    var counter = 0;
    return function () {return counter += 1;} //inner or closure function
})();
add(); //Outputs 1
add(); //Outputs 2
add(); //Outputs 3

Explanation : In above code its Self firing function that executes outer function once and returns anonymous closure inner function that does not executes at first time but maintains connection
with outer function.



Solution 2 :

var add = function(){ //Outer Function
    var counter = 0;
    return function(){  //Inner or closure Function 
      counter += 1;
      console.log(counter)
    }
  }
  var yo = add()
  yo() //output 1
  yo() //output 2
  yo() //output 3

Explanation :   When we assigned add() function to variable inner function will be assigned to variable yo,Then by just doing yo() we will fire inner function


Conclusion : Its just game of inner and outer function , where outer function executes itself by returning inner/closure function ,and at end its inner/closure function left to be executed

No comments :

Post a Comment