Sub topic 6
How Closures Keep Data Alive
This chapter assumes you know how JavaScript closures and lexical scope work, and that you have read the earlier chapters on reachability and mark-and-sweep. Garbage collection roots are the starting points the collector traces from, such as globals and the current call stack. An object survives as long as a path from a root reaches it. A closure is one of the less obvious places such a path can pass through.
What a Closure Actually Holds
A closure is a function together with the scope it was created in. The function does not copy the values of the outer variables. It keeps a reference to the variables themselves, and those variables live in a scope object. V8 calls this scope object a Context, and the language specification calls it an environment record.
That reference gives you an extra kind of path from a root to your data:
function createHandler() {
const bigData = new Array(1_000_000).fill(0);
return function handler() {
return bigData.length;
};
}
const handler = createHandler();
// bigData stays in memory for as long as handler is reachable.The path is handler (a global binding, so a root) → the function object → its Context → bigData. After createHandler returns, its stack frame is gone, but the Context it created stays alive. It ends up on the heap, held by handler. Once nothing reaches handler any more, the Context and the array become unreachable and the collector can free them.
Captured variables are live, not snapshots
Because a closure references variables rather than values, the data it retains can change after the closure is created:
function makeCounter() {
let count = 0;
const history = [];
return function increment() {
count += 1;
history.push(count); // history grows with every call
return count;
};
}
const inc = makeCounter();
inc();
inc();
console.log(inc()); // 3The memory this closure retains is whatever history holds right now, and it grows with every call. A closure that appends to a captured array or map is an unbounded cache under another name.
Where Captured Variables Live
Engines do not move every local variable to the heap. V8 sorts each function's variables while parsing it:
| Variable is... | Where V8 stores it | Lifetime |
|---|---|---|
| Used only by the function itself | Stack slot or register | Ends when the call returns |
| Referenced by any inner function | The function's Context object on the heap | As long as any closure (or other path) reaches the Context |
| Anywhere in a scope that contains direct `eval` | Context object | Same as above, for every variable in that scope |
The middle row is the important one. The question V8 asks is whether any inner function references the variable. It does not ask which inner function references it.
The Shared Context Gotcha
All closures created in the same scope during the same call share a single Context object. So if one inner function uses a large variable, every sibling closure keeps that variable alive, including closures that never mention it.
function setup() {
const bigData = new Array(1_000_000).fill(0);
function logSize() {
console.log(bigData.length); // forces bigData into the shared Context
}
logSize();
return function tick() {
return Date.now(); // never touches bigData
};
}
const tick = setup();
// tick keeps the shared Context alive, and the Context holds bigData.logSize is unreachable once setup returns. Even so, bigData stays alive: it sits in the Context that tick also references. V8 does not keep a separate, trimmed Context for each closure. Doing so would cost extra memory and allocation time on every function call.
How shared contexts form a chain
This behavior caused a well-known leak, first reported by the Meteor team. You can reproduce it in Node.js:
// Run with: node --expose-gc chain-leak.js
let theThing = null;
function replaceThing() {
const originalThing = theThing;
function unused() {
if (originalThing) console.log("never called");
}
theThing = {
payload: new Array(1_000_000).fill(0),
someMethod() {
console.log("method");
},
};
}
const toMB = (b) => (b / 1024 / 1024).toFixed(1);
for (let i = 0; i < 20; i++) {
replaceThing();
if (global.gc) global.gc();
console.log(`call ${i + 1}: heapUsed ${toMB(process.memoryUsage().heapUsed)} MB`);
}Every call allocates a new theThing, so you might expect the old ones to be collected. They are not. unused references originalThing, which puts originalThing into the Context for that call. someMethod was created in the same call, so it shares that Context. The result is a chain: the global theThing → someMethod → Context → originalThing (the previous theThing) → its someMethod → its Context → and so on, back to the first call. On current V8 the reported heap grows by several megabytes on each call and never drops.
There are two fixes. You can stop referencing originalThing from any inner function. Or you can break the chain explicitly by adding originalThing = null; (after changing it to let) at the end of replaceThing. Clearing the variable empties its Context slot, so later closures no longer reach the previous object.
Other Things Closures Capture
thisin arrow functions. An arrow function takesthisfrom its enclosing scope. If you store an arrow callback inside a long-lived structure, it keeps the surrounding instance alive, along with everything that instance references.- Loop bindings. In a
for (let i ...)loop, each iteration gets a new binding and a new Context. If you create 10,000 closures in such a loop, you get 10,000 small Contexts. - Direct
eval. Inside a function that callseval(...)directly, any variable might be looked up at runtime. V8 therefore context-allocates every variable in that scope, so a closure created there retains all of them. - Debugging tools. When DevTools is paused, it can show and sometimes keep extra scope variables. Measure memory with the debugger detached, or your numbers may be off.
Patterns That Retain Less
Copy out what you need
If a closure needs one fact about a large value, compute that fact first and capture only the result:
function createHandler() {
const bigData = new Array(1_000_000).fill(0);
const length = bigData.length; // small value, safe to capture
return function handler() {
return length;
};
}
const handler = createHandler();
// No inner function references bigData, so it lives only on the stack frame
// and becomes unreachable when createHandler returns.Narrow the scope
You can move the code that uses the large value into its own function. Its locals then live in a different scope from the closure you return:
function summarize(rows) {
return { count: rows.length, first: rows[0] };
}
function setup(rows) {
const summary = summarize(rows);
return function report() {
return `${summary.count} rows, first = ${summary.first}`;
};
}
const report = setup([10, 20, 30]);
console.log(report()); // "3 rows, first = 10"report does not capture rows directly. rows is a parameter of setup that no inner function references, so it is not context-allocated, and the closure retains only the small summary object.
Release long-lived closures deliberately
Callbacks registered with timers, event targets, or emitters are the closures most likely to outlive their usefulness. They stay reachable through the registry that holds them, so removing them is the only way to free what they capture. The chapter on common leak patterns covers the removal techniques. For this chapter, the point is that the cost of leaving a callback registered includes its whole Context.
Clear a variable when a closure must stay
If a closure has to live for a long time but only needs a large variable at the start, assign null to that variable once you are done with it. This works because the closure shares the variable itself: clearing it in any closure, or in the outer function, clears it for every function that shares the Context.
function createLoader(source) {
let raw = source;
let parsed = null;
return function get() {
if (parsed === null) {
parsed = raw.split(",").map(Number);
raw = null; // the original string can now be collected
}
return parsed;
};
}
const get = createLoader("1,2,3");
console.log(get()); // [1, 2, 3]Spotting Closure Retention in a Heap Snapshot
In a Chrome DevTools or Node.js heap snapshot, closures appear as (closure) entries. Expand one and you will find a context field. That field is the Context object, and you can open it to see every captured variable it holds. In the Retainers panel for a leaked object, a path that runs through context tells you a closure is responsible. The variable name on the edge (for example, originalThing) tells you which binding to clear or stop capturing. The heap snapshot chapter covers the full workflow.
Exercise
In the code below, does bigList stay in memory after init returns and only onTick is kept? Explain why, and give a one-line fix.
function init() {
const bigList = new Array(500_000).fill("x");
const check = () => bigList.includes("y");
check();
return () => Date.now();
}
const onTick = init();
Show answer
Yes. The arrow function check references bigList, so V8 stores bigList in the Context that init creates. The returned arrow function was created in the same scope, so it shares that Context. Keeping onTick therefore keeps bigList alive, even though onTick never uses it. One fix is to compute the result before creating any closure, for example const hasY = bigList.includes("y");, and remove check. Another is to change bigList to let and add bigList = null; after check().
Exercise
A closure captures a let variable. Later, the outer function assigns a 10 MB array to that variable. Does the closure keep the new array alive, or the value the variable held when the closure was created?
Show answer
It keeps the new array alive. A closure references the variable's slot in the Context, not a copy of its value. Whatever the variable holds at any moment is reachable through every closure that shares that Context.
Exercise
Why is unused in the replaceThing example responsible for the leak, even though it is never called and becomes unreachable as soon as replaceThing returns?
Show answer
Because unused references originalThing, V8 moves originalThing into the shared Context while it parses replaceThing, before anything runs. someMethod shares that Context and stays reachable through the global theThing. So each new object retains the previous one through its method's Context, which creates an unbounded chain. unused itself does not need to stay alive for this to happen.