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.
Loading...
See how JavaScript garbage collection works with an interactive visualization. Watch the mark-and-sweep algorithm, explore memory leak patterns with closures, timers, and DOM nodes, plus WeakRef.
Loading visualization...
JavaScript garbage collection automatically reclaims heap memory for unreachable objects, typically using tracing strategies like mark-and-sweep to prevent manual memory management.
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.
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.
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.
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.
Common interview prompts with concise model answers.
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.No. Modern tracing collectors handle unreachable cycles correctly. Leaks occur when references remain reachable from roots.
Use browser devtools heap snapshots, allocation timelines, and retained-size analysis to find unexpectedly reachable objects.
Deleting properties can help remove references, but leak prevention depends on the full reachability graph, not one operation.
Continue with these concepts to strengthen your mental model.
let x = { a: 1 };let y = { b: 2, ref: x };let z = { c: 3 };y.ref = null;z = null;// GC runs: mark from roots, sweep unreachableconsole.log(x.a);no roots
empty
No output yet.