1

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?

manifestor
  • 1,352
  • 6
  • 19
  • 34
  • 3
    `add` is the function returned by the first function, not the first function itself (that's only called once). It might help to give the inner function a name: `return function inner () {return counter += 1;}`. When you call `add()` you are calling `inner()` – Mark Apr 15 '18 at 17:35

1 Answers1

1

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)

Pac0
  • 21,465
  • 8
  • 65
  • 74