Functions as variable in Javascript [duplicate]
_counter
is the local variable within function counter()
. Every time when you call counter()
a new _counter
will be created.
But var createClosure = counter()
only called the function 1 time, that's why _counter
is not newly created every time and 'remembered' there (that's where closure happens)
Each time you call counter()()
, it creates a new function and a new closure.
So the result is always 0
.
On the contrary, when var createClosure = counter();
is executed, a function and closure are created and saved in the variable createClosure
. Next time when you call createClosure()
, the saved one is invoked and the created closure is used. Therefore the results are 0
, 1
, 2
, 3
, ...
To put in another way, the return value of the counter()
function, which is the closure, isn't persisted or rather it is discarded when you simply call the function as is.
However after assigning that return value to
var createClosure
. You are able to call the closure as many times as needed