Memory Leaks in JavaScript

Difficulty: Advanced

Question

What causes memory leaks in JavaScript applications, and how do you detect and fix them in the browser and in Node.js?

Answer

A memory leak in JavaScript is memory that your program no longer needs but that the garbage collector cannot free because something still references it. JavaScript engines use reachability-based (mark-and-sweep) garbage collection, so a leak is almost always an unintended reference from a live root, such as a global variable, an active timer, an event listener, a closure or a long-lived cache. You find leaks with heap snapshots and allocation timelines in Chrome DevTools or the Node.js inspector, and fix them by removing the reference at the right lifecycle moment.

How garbage collection decides what to keep

V8 starts from roots (the global object, the current call stack, active handles like timers and sockets) and marks everything reachable from them. Anything unmarked is swept. Circular references alone do not leak: two objects pointing at each other but unreachable from a root are collected. So the question is always "which root is still holding this?"

The usual suspects

  1. Forgotten event listeners: a component adds window.addEventListener('resize', handler) and never removes it. The handler's closure keeps the component's data alive after it unmounts.
  2. Timers and intervals: setInterval callbacks run forever unless cleared, along with everything they close over.
  3. Detached DOM nodes: an element removed from the page but still referenced by a JS variable, array or cache. The entire subtree stays in memory.
  4. Accidental globals: assigning to an undeclared variable in sloppy mode creates a property on window. ES modules and strict mode turn this into a ReferenceError.
  5. Unbounded caches and maps: a Map of session data or memoized results that only grows. Common in Node.js servers that run for weeks.
  6. Closures holding large data: a small callback that captures a big array or response object it does not actually need.
  7. Subscriptions: WebSocket, RxJS, Firebase or store subscriptions not unsubscribed on unmount.

Detecting a leak

Prevention patterns

Leak sourceFix
Event listenersremoveEventListener in cleanup, or pass { signal } from an AbortController and call abort()
TimersclearInterval / clearTimeout in cleanup (React useEffect return)
Detached DOMNull out references, or store element metadata in a WeakMap
CachesLRU with a max size, TTLs, or WeakMap keyed by objects
SubscriptionsAlways keep and call the unsubscribe function

In React, the useEffect cleanup function is where nearly all of these fixes go.

Mark-and-sweep, and what defeats it. Try the Map, setInterval and accidental-global leaks under Tweak.
  1. Mark: Everything reachable from the roots is marked.
  2. Sweep: Unmarked objects are freed.
  3. Timer leak: An un-cleared setInterval keeps its closure and captured data alive.
  4. Map and global leaks: Strong Map keys and accidental globals stay reachable forever.

Code examples

Listener and timer leak fixed with AbortController and cleanup

// Leaky: listener and interval outlive the widget
function mountPriceTickerLeaky(el) {
  const history = new Array(100_000).fill(0); // big closure data
  window.addEventListener('resize', () => el.style.width = `${history.length}px`);
  setInterval(() => { el.textContent = `Rs ${Math.random().toFixed(2)}`; }, 1000);
}

// Fixed: one AbortController removes every listener; return a cleanup
function mountPriceTicker(el) {
  const controller = new AbortController();
  const { signal } = controller;

  window.addEventListener('resize', () => { /* resize logic */ }, { signal });
  el.addEventListener('click', () => { /* open details */ }, { signal });
  const timer = setInterval(() => { el.textContent = 'tick'; }, 1000);

  return function unmount() {
    controller.abort();     // removes both listeners
    clearInterval(timer);   // stops the timer and frees its closure
  };
}

// React equivalent
// useEffect(() => mountPriceTicker(ref.current), []);

Passing an AbortSignal to addEventListener lets you remove many listeners with one abort() call. Returning a cleanup function matches how React's useEffect expects teardown to work.

Detached DOM and unbounded cache in Node.js

// Detached DOM: removed from the page but still referenced
const removedRows = [];
function deleteRow(row) {
  row.remove();
  removedRows.push(row); // leak: whole subtree stays in memory
}
// Fix: do not keep the node, or store metadata in a WeakMap keyed by it
const rowMeta = new WeakMap();

// Node.js: a per-request cache that only grows
const sessions = new Map();
function onRequest(req) {
  sessions.set(req.id, { body: req.body, at: Date.now() }); // never deleted
}

// Fix: evict on a schedule (or use an LRU / Redis with TTL)
const TTL_MS = 15 * 60 * 1000;
setInterval(() => {
  const now = Date.now();
  for (const [id, s] of sessions) if (now - s.at > TTL_MS) sessions.delete(id);
}, 60_000).unref(); // unref so the timer does not keep the process alive

setInterval(() => {
  const { heapUsed } = process.memoryUsage();
  console.log('heapUsed MB', (heapUsed / 1024 / 1024).toFixed(1));
}, 30_000).unref();

Arrays and Maps that hold DOM nodes or request data are the most common real leaks. Bounded eviction and logging heapUsed over time make growth visible before the process crashes.

Key points

Common follow-up questions

Interview tips

Concepts covered

Memory Leak, Garbage Collection, Mark-and-Sweep, Detached DOM, Event Listeners, Heap Snapshot

More JavaScript Interview questions