Learning on Web Dev Open is free for all.

Systems Thinking > What a variable actually holdsWhat the collector cannot free
Phase 03What a variable actually holds138 of 434

What the collector cannot free

Garbage collection is automatic and leaks are still yours. Four patterns account for most of them in browser code.

Concept14 minAI pair

The rule is reachability, not reference counting: anything reachable from a root, the global object, the current stack, live DOM, survives; everything else is collectible. You cannot free memory, and you cannot ask for a collection. All you control is what stays reachable.

The four patterns worth knowing by name. Event listeners attached to something long-lived and never removed. Timers and intervals that keep a callback, and therefore its scope, alive forever. Detached DOM nodes still referenced by an array or a map after being removed from the document. And caches with no eviction policy, which are leaks with a respectable job title.

WeakMap and WeakSet exist for the case where you want to associate data with an object without keeping that object alive: metadata keyed by DOM node is the canonical use. They are not a general-purpose cache and they are not enumerable, deliberately, because letting you observe collection would make it observable behaviour the engine has to guarantee.

You should now be able to

  • Explain reachability as the rule the collector actually applies
  • Name the four common retention patterns in front-end code
Ask the community

Loading…