function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2
A closure is a function plus the variables from the place where it was created. The function can still read and change those variables after the outer function has returned.
Every JavaScript function forms a closure. It matters when an inner function lives longer than its parent function.
Example: a counter factory. makeCounter() declares let count = 0 and returns a function that increases it. Each returned function keeps its own private count. No other code can touch it. Think of it as a backpack: the function carries its variables with it wherever it goes.
Closures are used for:
- data privacy, like the private
countabove - function factories that build custom functions
- memoization caches that remember earlier results
- event handlers and callbacks that remember context
- utilities like
debounce, which keep a timer between calls
The cost: captured variables stay in memory as long as the function can still be reached.
- A function keeps access to the scope where it was written, even after the outer function returns.
- Variables are captured by reference, not copied, so the function sees later changes.
- Each call to the outer function creates a new, separate scope.
- Closures are used for privacy, factories, memoization and callbacks.
Read more
- Closures (MDN) (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)developer.mozilla.org
- Variable scope, closure (https://javascript.info/closure)javascript.info