Why can a returned function keep a large string alive when it never reads that string? A closure preserves access to its enclosing lexical environment after the enclosing function returns. That access can also preserve paths to objects the function does not appear to need. section 6.4
In V8, a function that captures outer variables can point through its [[Environment]] slot to a heap-allocated Context. The Context survives while a function references it, so captured state survives its original call. This is useful for private state. Exactly which unused variables remain in that state is an implementation detail: engines can differ, and optimizations are not guaranteed. section 6.4 section 9.6
function processData() {
const str = 'a'.repeat(1_000_000);
const id = generateId();
processStr(str);
return function getId() {
return id;
};
}
const getId = processData();The returned getter reads only the ID, yet the large processed string is created in the same scope. Do not rely on the engine to discard it from the closure’s retained state. section 6.4
Limit the lifetime and reachability of data a closure does not need:
- Move large-object processing into a separate function or scope, then create the closure around only the small value it needs. section 6.4 section 9.1.1
- Remove registered callbacks when their work ends. A listener or registry that remains reachable can keep its callback—and potentially its enclosing state—alive. section 6.4 section 9.6
Closures also explain loop surprises. Callbacks created in a `var` loop share the loop variable and can all observe its later value; the supplied `let` version gives each iteration its own binding. Distinguish that binding behavior from memory retention: both follow from which environment a callback can access, but they produce different bugs. section 6.4
Setting a variable to `null` removes one route to an object, not every route. For memory problems, ask what still references the callback and what the callback’s environment might retain. Prefer making unwanted objects inaccessible to the closure in the first place. section 9.1.1 section 9.6























