Garbage Collection
15 min read
Mark-and-SweepReference CountingMemory LeaksWeakRefWeakMap
Garbage Collection in JavaScript
JS automatically frees memory that is no longer reachable. The primary algorithm is Mark-and-Sweep.
Mark-and-Sweep
- Start from roots (global object, call stack variables)
- Mark all reachable objects
- Sweep (free) all unmarked objects
Common Memory Leaks
- Forgotten event listeners
- Closures holding large objects
- Detached DOM nodes
- Global variables
- Timers (setInterval without clearInterval)
WeakRef and WeakMap
WeakRef holds a reference that does not prevent garbage collection. WeakMap keys are weakly held — perfect for caches.