Tech Interview RoomStudy guides

JavaScript

How does garbage collection work in JavaScript and what causes memory leaks in web apps?

Advanced · 2 min read · Lesson 12 of 12 in JavaScript

JavaScript engines use reachability: an object is kept while it can be reached from a root (global object, current call stack, active closures). V8 uses a generational collector: a fast "scavenger" for the young generation, where most objects die young, and mark-sweep-compact for the old generation, run mostly incrementally and concurrently to avoid long pauses. Reference cycles are not a problem: unreachable cycles are collected.

Common leaks in frontend apps

  • Event listeners on window or document not removed when a component unmounts.
  • Timers (setInterval) that are never cleared and keep their closure alive.
  • Detached DOM nodes: removed from the page but still referenced from JavaScript (a cache or array).
  • Global caches or maps that only grow. Use WeakMap/WeakSet when keys are objects whose lifetime you do not control.
  • Subscriptions (WebSocket, store, observable) not unsubscribed.
  • Closures that capture large objects and live long.

Finding them

Chrome DevTools > Memory: take a heap snapshot, do the action several times, take another, and compare. Filter for "Detached" to find detached DOM trees. The Performance panel's memory track shows a sawtooth that keeps climbing when something leaks.

Example

js
// Leak: listener and interval live forever
function mountBad(el) {
  const big = new Array(1e6).fill('*');
  window.addEventListener('resize', () => el.textContent = big.length);
  setInterval(() => console.log(big.length), 1000);
}

// Fixed: everything is torn down on unmount
function mountGood(el) {
  const controller = new AbortController();
  const onResize = () => { el.textContent = String(window.innerWidth); };
  window.addEventListener('resize', onResize, { signal: controller.signal });
  const id = setInterval(onResize, 1000);
  return () => { controller.abort(); clearInterval(id); };   // cleanup
}

Returning a cleanup function is exactly the shape of a React useEffect cleanup or Vue onUnmounted.

Follow-up questions interviewers ask

Try answering each one before you open it.

When would you use WeakMap or WeakRef?

WeakMap stores metadata about objects (for example DOM nodes) without keeping them alive: when the key is collected, the entry disappears. WeakRef and FinalizationRegistry allow a cache that lets the GC drop values. They are rarely needed and non-deterministic, so do not use them for program logic.