Intermediate · 4 of 17 · 9 min read
Closures
Why a function remembers the variables around it, and the three places that memory surprises people.
- Closures
A closure is what you get every time a function is defined inside another one. The inner function keeps access to the outer function’s variables — and keeps it after the outer function has returned. That second half is the whole subject.
What a closure captures
Start with the version that behaves the way everyone expects:
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = makeCounter();
console.log(counter(), counter(), counter()); // 1 2 3
makeCounter has finished running by the time you call counter(). Normally its local variables
would be gone — the stack frame was popped. They are not gone, because the returned function still
references count, and the engine keeps anything still reachable.
Now the part that trips people up. The closure holds a reference to the variable, not a snapshot of what was in it:
function make() {
let n = 0;
const read = () => n;
n = 42; // changed after `read` was created
return read;
}
console.log(make()()); // 42, not 0
If a closure copied values, that would print 0. It prints 42 because read and the assignment
are talking about the same n.
The loop trap
This is the most-asked closure question in interviews, and it is really a question about how many variables exist:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3, 3, 3
There is exactly one i. var is function-scoped, so the loop does not create a new binding per
iteration — all three callbacks close over the same variable. By the time the timers run, the loop
has finished and that one variable holds 3.
let is block-scoped, and a for loop with let creates a fresh binding each iteration:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 0, 1, 2
Before let existed, the fix was to create the extra scope by hand with an immediately-invoked
function — which is worth recognising, because you will meet it in older code:
for (var i = 0; i < 3; i++) {
((n) => setTimeout(() => console.log(n), 0))(i); // 0, 1, 2
}
| Bindings created | Each callback sees | |
|---|---|---|
var i |
one, for the whole function | the same variable, final value |
let i |
one per iteration | its own variable |
var + IIFE |
one per call, as a parameter | its own parameter |
Private state
The reason closures matter in real code is not the puzzles — it is that a closed-over variable is genuinely unreachable from outside. No convention, no underscore prefix, no trust required:
function createCounter() {
let count = 0;
return {
increment: () => ++count,
read: () => count,
};
}
const c = createCounter();
c.increment();
console.log(c.read()); // 1
console.log(c.count); // undefined — there is no way in
That is the Module pattern, and it is how JavaScript had encapsulation for twenty years before
#private class fields arrived. It is also what makes a memoisation cache, a rate limiter, a
debounce and an event subscription work — each of them is a function holding private state.
Closures and memory
A closure keeps its captured scope reachable, which is a feature right up until it is a leak:
let handler;
function attach() {
const big = new Array(1e6).fill('x'); // captured by the closure below
handler = () => big.length;
}
attach();
// `big` cannot be collected while `handler` exists.
handler = null; // now it can
This is the mechanism behind the classic “forgotten event listener” leak: the listener closes over a scope that reaches a large object or a DOM node, and as long as the listener is registered, none of it can be freed. Removing the listener releases the closure, and the whole graph becomes collectable.
Common mistakes
Assuming the closure copied the value
Mistake: expecting 0, 1, 2 from a var loop, or 0 from the make() example above.
Why it fails: the closure shares the variable; reading it happens when the inner function runs,
not when it was created.
What to do instead: use let in loops, or pass the value in as a parameter so it genuinely is a
copy.
Reaching for a closure where a parameter would do
Mistake: wrapping everything in a factory to “hide” variables that nobody was going to touch. Why it fails: it adds a layer of indirection and an extra call for no privacy anyone needed. What to do instead: closures are for state that must persist between calls. For state that lives for one call, that is just a local variable.
Forgetting that the captured scope stays alive
Mistake: registering a long-lived callback that closes over something expensive. Why it fails: the garbage collector frees what is unreachable, and your callback is what makes it reachable. What to do instead: unregister the callback when you are done, and keep captured scopes small — capture the one field you need, not the whole object.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does a closure actually capture?
This is the single most famous JavaScript interview bug, and it is really a question about how many variables exist.
This was meant to log 0, 1, 2 but logs 3, 3, 3. Why?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}What is the most common practical use of a closure?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.