What a closure is
A closure is a function bundled with references to variables from its outer lexical scopes. Those bindings outlive the outer function call if the inner function escapes (returned, stored, or passed to setTimeout).
function makeCounter() {
let n = 0;
return function inc() {
n += 1;
return n;
};
}
const c = makeCounter();
console.log(c()); // 1
console.log(c()); // 2Open in Visualizern is not copied into inc; both calls mutate the same binding. That distinction — binding vs snapshot — explains the timer bug below.
The for + var + setTimeout bug
var is function-scoped. The loop reuses one i. Each timeout callback closes over that same binding. By the time macrotasks run, the loop finished and i is 3:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints 3 3 3Open in VisualizerFixes: let, IIFE, forEach
let in a for head creates a new binding per iteration:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints 0 1 2Open in VisualizerPre-let code used an IIFE to capture the value:
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 0);
})(i);
}
// prints 0 1 2Open in VisualizerPractical pattern: private state
Modules and factory functions use closures for encapsulation without classes. Prefer that when the API is a small set of functions sharing state. Avoid nesting closures deeply just to hide a single boolean — readability suffers and accidental retention of large objects becomes harder to spot.
When not to force closures
If you only need a value later, pass it as an argument. If you need many instances with methods, a class or explicit object may communicate lifetime better. Closures are a tool for lexical capture — not a substitute for clear data flow.