Closures: functions that remember
A function returns, yet a variable it declared keeps counting on the next call. Here is where that variable actually lives, drawn one call at a time.
01 A variable that outlives its function
makeCounter declares count, returns, and is finished. Yet every call to counter still reads and changes that count.
02 The picture that fails
The usual mental model says a function’s local variables live in its frame on the call stack, and the frame is thrown away when the function returns. If that were the whole story, count would be gone after makeCounter() returned, and counter() would have nothing to increment.
counter() would throw or start from nothing every time.03 What really happens: scopes and a hidden link
Each call to a function creates a new scope (the spec calls it an environment record) holding that call’s variables. Every function object also stores a hidden reference, written [[Environment]] in the spec, to the scope it was created in. When code reads a name, the engine looks in the current scope, then follows those links outward until it finds it. A function together with that remembered scope is a closure.
- just created
- running
- found via the link
- looked up
The script starts. Nothing has been called, so there is no frame for makeCounter and no scope for it yet.
In V8 (Chrome, Node), only variables that some inner function uses are moved into a heap-allocated context. Locals nobody captures can stay in the stack frame or in registers. The behaviour is the same in every engine; the storage is an implementation detail.
04 Every call gets its own scope
The scope belongs to a call, not to the function’s source code. Call makeCounter twice and you get two scopes, each with its own count.
- kept alive by a closure
a and b were made by the same code, but each call to makeCounter built its own scope. a only ever sees the first one.
05 See the closure yourself
Paste counter.js into the Chrome DevTools console, call counter() a couple of times, then inspect the function.
Expand the entry and open [[Scopes]]. You will find an entry like Closure (makeCounter) {count: 2}: that is the scope from the trace, held by the function. [[Scopes]] is a DevTools view, not something your code can read.
06 Closures capture variables, not values
A closure holds the scope, so it sees the variable’s value at the time it runs, not when it was made. The classic place this shows up is a loop that schedules callbacks.
for (var i = 0; i < 3; i++) {setTimeout(() => console.log(i));}// 3 3 3
for (let i = 0; i < 3; i++) {setTimeout(() => console.log(i));}// 0 1 2
var is scoped to the whole function, so all three callbacks share one i, which is 3 by the time they run. A let in a for header gets a fresh binding on every iteration, so each callback closes over its own i.
07 When it bites
let name = 'Ana';
const hi = () => name;
name = 'Bo';
hi(); // 'Bo'Reading a value that changed laterThe closure reads name when it runs. If you need a snapshot, copy it into a const inside the scope you close over.function load() {
const big = new Array(1e6);
return () => big.length;
}Keeping big data aliveAs long as the returned function is reachable, so is big. Store only what the closure needs, or drop the function when you are done with it.el.addEventListener('click', () => {
render(state);
});Listeners that are never removedThe element keeps the listener, the listener keeps its scope, and the scope keeps everything in it. Call removeEventListener or pass an AbortSignal when the component goes away.useEffect(() => {
setInterval(() => log(count), 1000);
}, []);A stale value in ReactThe callback closed over count from the first render. Later renders make new scopes it never sees. List count as a dependency or use the updater form of the setter.In V8, closures created in the same scope share one context. If one inner function captures a large object, it stays alive while any sibling closure from that scope is reachable, even one that never mentions it.