intermediate

Memory leaks, WeakMap, and WeakSet

Leaked listeners, timers, caches, detached DOM, closure retention, and weak associations.

Leaks happen when data stays reachable after it is no longer useful. Common frontend causes: forgotten event listeners, intervals, global caches, detached DOM nodes, and closures holding large graphs.

`WeakMap` keys must be objects; keys are weakly held and not enumerable — good for object-associated metadata without preventing collection. `WeakSet` tracks object membership weakly.

Weak collections do not fix leaks if the value closes over the key or another strong reference remains.

On interviews, explain the concept with a concrete example and name the runtime behavior interviewers probe.

Common pitfalls include mixing similar APIs and forgetting edge cases during live coding.

The trade-off is often clarity versus performance or safety versus convenience.

Checklist:

  • Clean lifecycle resources.
  • Bound cache size for strong Maps.
  • Use WeakMap for per-object metadata.