js
function counter() {
let n = 0;
return () => ++n;
}
const next = counter();
next(); // 1
next(); // 2
The inner arrow keeps n alive because it still references it. This is the building block for module patterns, memoization, and event handlers.
Interview questions
Sign in to saveWhat is a common memory pitfall with closures?
Long-lived closures can pin large scopes in memory. Only capture what you need, especially inside event listeners on removed DOM nodes.
Practice
Implement `once(fn)` so `fn` runs at most one time and later calls return the first result.
