Skip to content

Lesson 5 of 9 · 24m

Closures: Capture Semantics and Memory Behavior

Closures as live environment references — loop capture, accidental retention, and the practical difference between elegant encapsulation and leaks.

A closure is not a copy of variables. It is a function plus a live reference to the lexical environment where it was created. That design gives JavaScript powerful encapsulation and callbacks; it also creates the classic loop bug and a steady stream of memory leaks in long-lived applications.

Capture the binding, not the value

function counter() {
  let count = 0;
  return {
    inc() { count += 1; },
    value() { return count; },
  };
}

const c = counter();
c.inc();
c.value(); // 1

Both returned methods close over the same environment, so they observe the same mutable count. Nothing copied the value. The object returned is just the public face of a private environment.

The loop mistake everyone meets once

const handlers = [];
for (var i = 0; i < 3; i++) {
  handlers.push(() => i);
}
handlers.map(fn => fn()); // [3, 3, 3]

With var, one binding is shared by every closure. With let, each iteration gets a fresh binding:

for (let i = 0; i < 3; i++) {
  handlers.push(() => i);
}

That is not magic; the spec creates per-iteration lexical environments for the loop. The same issue appears with asynchronous callbacks inside loops, where the callback runs after the loop has finished.

Closures retain what they can reach

The specification reasons about environments, not individual variables. Engines optimize aggressively, but conservative captures can still retain large objects:

function attach(largeBuffer) {
  const firstByte = largeBuffer[0];

  button.onclick = () => {
    console.log(firstByte);
    audit.log(largeBuffer.length); // keeps largeBuffer reachable
  };
}

In a UI that survives for hours, an event listener closure can retain DOM trees, request payloads, and caches long after the feature visually disappeared. Removing a DOM node is not enough if a listener or timer still references the closure graph.

Closures are a module primitive

Before ES modules, the module pattern was a closure:

const store = (() => {
  const values = new Map();
  return {
    set: (key, value) => values.set(key, value),
    get: key => values.get(key),
  };
})();

The same primitive still matters. Factory functions, memoized selectors, middleware, and small state machines often need closure privacy more than they need classes.

Field notes

  • In heap snapshots, search for detached DOM nodes and repeated constructor names; then walk retainers back to the closure or listener holding them.
  • A memoization cache with no eviction policy is a closure-backed leak with good branding.
  • Capture narrow values (const id = user.id) rather than whole records when the large object is not semantically needed.
  • Beware closures in tests too: shared mutable setup often leaks state between cases through callbacks registered globally.

Was this lesson helpful?

Sign in to rate