How to define a javascript closure?
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
// Result: counter is 3
September 3rd, 2019
The variable add
is assigned the return value of a self-invoking function.
The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.