← Back to JavaScript, page 2

javascript-0038 · Hard senior

What causes memory leaks in JavaScript applications, and how do you find and fix them?

JavaScript frees memory only for objects that can no longer be reached from a root, so a leak is an object that is still reachable but no longer needed. Common causes are forgotten event listeners, timers, unbounded caches, detached DOM nodes, and closures that hold large data. Find them by comparing heap snapshots over time and fix them by removing the reference.

Full answer

The garbage collector works by reachability. Starting from roots such as the global object and the current call stack, it marks every object it can reach and frees the rest. A leak therefore is not memory that is "lost". It is memory that something still points to, even though the program will never use it again.

The usual sources are these:

  • Event listeners that are added and never removed. The listener keeps its closure alive, and the target keeps the listener.
  • setInterval or a long setTimeout that is never cleared, together with the data its callback uses.
  • Caches and registries that only grow: a Map of results keyed by user input, an array of logged events, or a module-level list.
  • DOM nodes removed from the page but still referenced from a variable or a closure (detached nodes).
  • Closures that capture a large object when only a small part is needed.
  • Global variables created by accident.

To find a leak, repeat the suspect action many times in a profiler, take heap snapshots before and after, and compare which object counts grow (Chrome DevTools Memory tab, or node --inspect for Node.js). The retainers view shows the chain of references that keeps an object alive.

Fixes are to remove the reference: use removeEventListener or an AbortSignal to drop listeners together, clear timers on teardown, bound caches with a size limit or an expiry, use WeakMap or WeakRef where the key's lifetime should decide, and copy only needed fields into closures.

javascript
import { getEventListeners } from 'node:events';

const bus = new EventTarget();

function mountWidget(signal) {
  const bigData = new Array(1000).fill('x'); // stays alive while the listener exists
  bus.addEventListener('update', () => bigData.length, { signal });
}

// Leaky version: nothing removes the listeners.
for (let i = 0; i < 5; i++) mountWidget();
console.log('listeners after 5 mounts without cleanup:', getEventListeners(bus, 'update').length);

// Fixed version: one controller removes everything it registered.
const fresh = new EventTarget();
const controller = new AbortController();
for (let i = 0; i < 5; i++) {
  fresh.addEventListener('update', () => i, { signal: controller.signal });
}
console.log('listeners before abort:', getEventListeners(fresh, 'update').length);
controller.abort();
console.log('listeners after abort:', getEventListeners(fresh, 'update').length);

// Unbounded cache versus a bounded one.
const unbounded = new Map();
const bounded = new Map();
const LIMIT = 3;
for (let i = 0; i < 10; i++) {
  unbounded.set(`query-${i}`, i);
  bounded.set(`query-${i}`, i);
  if (bounded.size > LIMIT) bounded.delete(bounded.keys().next().value); // drop the oldest
}
console.log('unbounded size:', unbounded.size, 'bounded size:', bounded.size);

// Timers: an interval keeps its callback alive until it is cleared.
let ticks = 0;
const interval = setInterval(() => {
  ticks += 1;
  if (ticks === 2) {
    clearInterval(interval);
    console.log('interval cleared after', ticks, 'ticks');
  }
}, 5);

Run with Node.js v24.22.1 as js-38.mjs; two runs gave identical output. Output: listeners after 5 mounts without cleanup: 5 listeners before abort: 5 listeners after abort: 0 unbounded size: 10 bounded size: 3 interval cleared after 2 ticks

Key points

  • A leak is a still-reachable object that the program no longer needs.
  • Main causes: listeners, timers, unbounded caches, detached DOM nodes, large closures.
  • Heap snapshot comparison shows what grows; retainers show why.
  • AbortSignal can remove many listeners at once.
  • Bound caches and weak references limit growth.

Common mistakes

  • Saying JavaScript has no memory leaks because it has garbage collection.
  • Removing a DOM node but keeping a reference to it in a variable or array.
  • Passing a new function to removeEventListener, so it does not match the one that was added.
  • Guessing at the cause instead of comparing heap snapshots.

Follow-ups

  • How do WeakMap and WeakRef help, and what are their limits?
  • How would you detect a leak in a long-running Node.js server?
  • Why can a closure keep a whole scope alive even though it uses only one variable?

Tips

  • Define a leak as "reachable but unneeded"; it shows you understand how collection works.
  • Describe a profiling workflow: baseline, repeat the action, snapshot, compare, check retainers.
  • Give two fixes with code names: AbortSignal for listeners and a size limit for caches.