liveBook · Manning

Closure

As explained in JavaScript in Depth

A function together with the lexical environment whose variables it can access after that environment's enclosing execution has ended.

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

How JavaScript in Depth covers it

How deep it goes
Traces [[Environment]] references to V8 heap Contexts while distinguishing possible unused-variable retention from specification guarantees.
Examples
Uses an ID getter beside a large string, loop-created callbacks, a delayed request notification, and a registered error handler.
What it assumes
Assumes familiarity with JavaScript functions and enclosing scope; develops the heap Context mechanism behind variable access.
What you can do after
Diagnose/debug with it by tracing callback lifetime and isolating large objects from scopes that callbacks can retain.
How it connects
Connects lexical scope and function objects to garbage-collection reachability, event listeners, and FinalizationRegistry callbacks.

Also explained in

Compare how 24 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.