Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function makeCounter() {
// `i` is only accessible inside the closure created when the
// `makeCounter` function is invoked.
var i = 0;
return function() {
console.log( ++i );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`,
// because the closure containing `i` is created when the function
// `makeCounter` is invoked.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2
i; // ReferenceError: i is not defined (it only exists inside the closures)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.