I've been trying to learn about closures, but one thing still perplexes me. If I have the following code:
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// Returns "3"
If I call add() three times, why dosen't it set counter to zero every time, then return the anonymous funtion that increments counter by one? Does it skip over it once the self-invoking function runs? Sorry if the question seems simple, I'm having a hard time understanding it. Any help would be greatly appreciated.
By calling
add()
you are not actually executing outer function but instead you are executing inner function. For inner functtion, counter is like a global variable that has been set once to0
and then it was never set again to0
. On callingadd()
you are executing lines inside inner function thus increamenting counter.The value assigned to
add
is the result of the IIFE, in which the closure was created. Maybe it's more obvious what will happen whenadd()
is called, when its creating is written as follows (equivalent to your original code):Because
add
is that anonymous function, because the function containingcounter
got called and its result was assigned toadd
:If you didn't call it:
...then
add
would do what you said, it would return a new function with its own counter, each time you called it:That's not resetting
counter
, that's creating a new counter each time.