Scope and closures
Scope and closures
Global, function and block scope determine where bindings are visible. A closure occurs when a function retains access to variables from its surrounding lexical scope. Closures are useful for private state and callbacks.
Try it yourself
Change the example, run it, and explain the result in your own words. Then create one variation of your own.
Key idea
Use the example as a starting point, not something to memorize. Practise, inspect the result and make small improvements.
Code example
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
console.log(next(), next());