Garbage Collection Theory
JavaScript garbage collection automatically reclaims heap memory for unreachable objects, typically using tracing strategies like mark-and-sweep to prevent manual memory management.
What it is
JavaScript engines track object reachability from roots such as global objects, active stack frames, and live closures.
If an object can no longer be reached through any reference path, it becomes collectible and its memory can be reused.
Automatic collection reduces manual memory bugs, but developers still influence memory behavior through references, caches, listeners, and long-lived closures.
Interview framing: define Garbage Collection in one sentence, then explain one concrete runtime behavior and one common pitfall with a short code example.
How it works
- Step 1: the collector starts from roots and marks reachable objects.
- Step 2: it recursively traverses references to mark everything still in use.
- Step 3: unmarked objects are considered unreachable and reclaimed.
- Step 4: the runtime may compact memory and repeat collection cycles incrementally over time.
Common mistakes
Expecting immediate memory release after setting a variable to null
Nulling a reference only makes an object eligible for collection if no other reachable references exist.
Fix: Remove all strong references and let the collector run naturally.
Leaking memory via timers and event listeners
Uncleared intervals or listeners can keep closures and large object graphs reachable indefinitely.
Fix: Pair every registration with cleanup logic during teardown or component unmount.
Misunderstanding WeakMap and WeakRef semantics
Weak references are not deterministic cleanup mechanisms and should not be used for critical program flow.
Fix: Use weak structures for cache hints only, not required lifecycle guarantees.
Interview questions
Common interview prompts with concise model answers.
Can JavaScript guarantee exactly when an object is collected?
No. Collection timing is engine-controlled and non-deterministic, optimized for throughput and responsiveness.
let cache = { payload: new Array(1_000_000).fill("x") };
cache = null; // eligible for GC when no other refs remain
// Collection timing is runtime-dependent.Do circular references always leak memory?
No. Modern tracing collectors handle unreachable cycles correctly. Leaks occur when references remain reachable from roots.
How can I diagnose memory leaks?
Use browser devtools heap snapshots, allocation timelines, and retained-size analysis to find unexpectedly reachable objects.
Is manual delete enough to avoid leaks?
Deleting properties can help remove references, but leak prevention depends on the full reachability graph, not one operation.
Related concepts
Continue with these concepts to strengthen your mental model.