How do closures retain access to variables after a function returns?
Explain closure capture through lexical environments, reachability, and mutation—not a vague “function remembers variables” rule.
Useful prerequisites
A function can keep using a variable even after the code that created the function has finished running. That surprises people when they first encounter callbacks, event handlers or factory functions. A closure is simply a function together with access to the lexical environment in which it was created.
A function can keep using a variable even after the code that created the function has finished running. That surprises people when they first encounter callbacks, event handlers or factory functions. A closure is simply a function together with access to the lexical environment in which it was created.
The quick version
A closure is a function together with access to the lexical environment in which it was created. The environment remains alive while it is reachable through the closure.
Build the mental model
The engine does not need to preserve an entire outer stack frame. It preserves the bindings that remain reachable. Closures observe bindings, not necessarily snapshots: if a captured binding changes, later calls can observe the new value.
See it in code
function counter() {
let value = 0;
return () => ++value;
}
const next = counter();
next(); // 1
next(); // 2
The returned function keeps the value binding reachable.
Where it gets tricky
The distinction between a binding and its current value matters in loops and callbacks. A let binding is created per loop iteration, while a var binding is shared by the containing function. Capturing a DOM node or large cache can keep its entire reachable graph alive; remove listeners and timers when their owner is disposed.
A common misunderstanding
Closures do not automatically cause memory leaks. A leak occurs when something retains a closure or captured object longer than intended.
What this changes in an application
Event listeners, timers, subscriptions, and cached callbacks can retain large object graphs. Cleanup is about removing unnecessary references, not avoiding closures.
Questions worth exploring next
- Why can a stale React callback happen?
- How would you release a closure retained by an event listener?
References and next steps
- Closures — primary or authoritative documentation for the underlying behavior.
- MDN Web Docs — use the relevant API reference for adjacent browser details.