Here it is:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// the counter is now 3
How it possible, that counter
is 3
when it is set to 0
everytime add
is called?
Here it is:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// the counter is now 3
How it possible, that counter
is 3
when it is set to 0
everytime add
is called?
counter
is set to zero only once, while defining a new function in the instruction var add = ....
After this instruction, add
is the function function () {return counter += 1;}
(a bit complicated if you are new, see linked potential duplicate for a general explanation).
So, when you call add() thereafter, you call only the code that increment the counter.
This function has accesss to the variable counter (that's what we call a closure, more or less, the variable counter is not defined globally, it's not defined in the small counter += 1
function, but it's nevertheless "taken with" the small function)