Closure counter

by Daman Daman

JavaScript

// The variable add is assigned the return value of a self invoking outer function.
var add = (function outer() {
    var counter = 0; 
    return function inner() { 
        return counter += 1;
    }
})();    // The self-invoking function outer only runs once. It sets the counter to 0, and returns an inner function expression. 

// Variable add then becomes an inner function. Only add can change the counter in the parent scope, even after the parent function has closed.
console.log(add())
console.log(add())
console.log(add())