Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Memory & Garbage Collection — JavaScript interview guide

3 / 23How JavaScript RunsMedium priorityMedium 20 min

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

Step 1/13
memory.js
▶let user = { name: "Sumit" };
2let admin = user;
3user = null;
4admin = null;
5// ...garbage collector runs
6
7function mount() {
8 const big = new Array(1000000);
9 window.addEventListener("resize", () => big.length);
10}
11mount();
12// ...garbage collector runs again
STACK & ROOTSHEAPwindow (global)rootuser→ object #1{ name: "Sumit" }object #1
Heap used< 1 KB
root reachable (marked) unreachable leak

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

  1. Take a heap snapshot of a page, add a leaking listener, and compare snapshots.

Keep learning