0

I am relatively new with the Javascript closure concept. I know how to get the work done, but I want to understand the concept through and through.

Can somebody explain in short, why example 1,2 works,and 3,4 doesn't? Any good links regarding js closures will be appreciated as well.

Example 1

    var add = (function() {
    var counter = 0;
    var plus = function() {
             return ++counter;
         };

         return plus;

     })();

    console.log(add()); //1
    console.log(add()); //2
    console.log(add()); //3

Example 2

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

add();//1
add();//2
add();//3

Example 3

var add=function(){
var counter=0;
var plus=(function(){
  return ++counter;
})();
return plus;

} 
 console.log(add());//1
 console.log(add());//1
 console.log(add());//1

Example 4

var add=function(){
var counter=0;
var plus=(function(){
  return ++counter;
});

return plus;
}


console.log(add()());//1
console.log(add()());//1
console.log(add()());//1
Tahniat Ashraf
  • 1,020
  • 2
  • 12
  • 21
  • https://stackoverflow.com/questions/111102/how-do-javascript-closures-work/ – CertainPerformance May 24 '18 at 07:24
  • 1
    in the example 3, the `plus` you return is not a function, but the result of the execution of the IIFE, so it's `1`. In the example 4 the `add` function is executed each time as a "new" one (it's a basic function declaration so it creates its variables each time), so that counter always start at `0` and ends up being `1` (actually exemple 3 is in the same situation too) – Kaddath May 24 '18 at 07:30
  • Thanks @CertainPerformance, kaddath -got my answer – Tahniat Ashraf May 26 '18 at 07:50

0 Answers0