Memory & Garbage Collection — JavaScript interview guide
Memory & Garbage Collection
JavaScript frees memory automatically when values can no longer be reached. Leaks happen when you accidentally keep references around.
See it run
Press Play, or step with Next. Follow the arrows: anything that cannot be reached from a variable or root is free to go.
Reachability, mark & sweep, and a real memory leak
▶let user = { name: "Sumit" };2let admin = user;3user = null;4admin = null;5// ...garbage collector runs67function mount() {8const big = new Array(1000000);9window.addEventListener("resize", () => big.length);10}11mount();12// ...garbage collector runs again
What happens:The object is created in the HEAP. The variable user lives on the stack and only holds a REFERENCE (an arrow) to it.
Explained simply
Stack and heap
Primitive values and function frames live on the stack. Objects, arrays and functions live in the heap; variables hold references to them.
Mark and sweep
The garbage collector starts from roots (global object, current call stack), marks everything reachable, and frees everything that was not marked.
Common memory leaks
Event listeners that are never removed, setInterval that is never cleared, global variables created by mistake, closures holding large data, and detached DOM nodes still referenced in JS.
// React example: always clean up
useEffect(() => {
const id = setInterval(tick, 1000);
window.addEventListener("resize", onResize);
return () => {
clearInterval(id);
window.removeEventListener("resize", onResize);
};
}, []);Remember this
- Unreachable = collectable.
- Remove listeners, clear timers, abort fetches on unmount.
- Use Chrome DevTools → Memory → Heap snapshot to find leaks.
Interview questions
Name three common causes of memory leaks in a frontend app.
Un-removed event listeners, uncleared intervals/timeouts, and references to removed DOM nodes or large data kept in closures or global caches.
Practice
- Take a heap snapshot of a page, add a leaking listener, and compare snapshots.
Keep learning
More in How JavaScript Runs