Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

JavaScript Memory Leaks and Garbage Collection: Causes, Detection and Fixes

Learn how JavaScript garbage collection works (mark-and-sweep, reachability), the most common memory leaks in browsers and Node.js, how to find them with Chrome DevTools, and how WeakMap and WeakRef help.

Sumit KumarUpdated Oct 11, 20265 min readJavaScript
JavaScript Memory Leaks and Garbage Collection: Causes, Detection and Fixes

JavaScript manages memory for you: you create objects and the engine frees them when they're no longer needed. But "no longer needed" really means "no longer reachable". If your code accidentally keeps a reference to something it will never use again, that memory is never freed. That's a memory leak, and in a long-running single-page app or Node.js server it slowly eats RAM until things get slow or crash.

How garbage collection works#

JavaScript garbage collection mark-and-sweep: objects reachable from roots are kept, unreachable objects are collected, and leaked references keep memory alive

Modern engines like V8 use a mark-and-sweep algorithm:

  1. Start from the roots: global variables, the current call stack, active closures and DOM nodes in the document.
  2. Mark every object reachable from a root by following references.
  3. Sweep: free every object that wasn't marked.
JavaScript
let user = { name: "Asha" };   // reachable through the variable 'user'
user = null;                    // no references left → eligible for GC

let a = {};
let b = {};
a.ref = b;
b.ref = a;                      // circular reference
a = b = null;                   // still collected: mark-and-sweep handles cycles

V8 also uses generational collection: most objects die young, so new objects live in a small "young generation" that's collected often and cheaply. Survivors are promoted to the "old generation", which is collected less often. Java's JVM works the same way; see JVM internals.

The six most common memory leaks#

1. Accidental globals#

JavaScript
function track() {
  visits = [];          // forgot let/const → becomes window.visits (in sloppy mode)
  visits.push(Date.now());
}

Fix: use ES modules or "use strict", which turns this into an error, and enable ESLint's no-undef rule.

2. Forgotten event listeners#

JavaScript
class Modal {
  open() {
    window.addEventListener("resize", this.onResize);   // added on every open...
  }
  close() {
    this.element.remove();                              // ...never removed
  }
  onResize = () => { /* uses this.element */ };
}

The listener holds this, and window holds the listener, so every closed modal stays in memory forever.

JavaScript
// Fix 1: remove it
close() {
  window.removeEventListener("resize", this.onResize);
  this.element.remove();
}

// Fix 2: AbortController removes many listeners at once
const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
window.addEventListener("keydown", onKey, { signal: controller.signal });
controller.abort();   // both listeners removed

3. Timers that never stop#

JavaScript
function startPolling(component) {
  setInterval(() => {
    component.refresh();   // keeps 'component' alive even after it's destroyed
  }, 5000);
}

Fix: keep the ID and call clearInterval when you're done. In React, return a cleanup function from useEffect:

JavaScript
useEffect(() => {
  const id = setInterval(fetchLatest, 5000);
  return () => clearInterval(id);
}, []);

4. Closures holding large data#

JavaScript
function createHandler() {
  const hugeData = new Array(1_000_000).fill("x");
  return function handler() {
    console.log(hugeData.length);   // closure keeps all of hugeData alive
  };
}
const handler = createHandler();

Fix: only capture what you need: const len = hugeData.length; and use len inside the closure.

5. Detached DOM nodes#

JavaScript
const cache = [];
function showRow(data) {
  const row = document.createElement("tr");
  row.textContent = data.name;
  table.appendChild(row);
  cache.push(row);   // row stays in memory even after table.innerHTML = ""
}

Once removed from the document, a node is "detached", but a JavaScript reference still keeps it (and its whole subtree) alive.

6. Unbounded caches#

JavaScript
const cache = new Map();
app.get("/user/:id", async (req, res) => {
  if (!cache.has(req.params.id)) {
    cache.set(req.params.id, await db.getUser(req.params.id));   // grows forever
  }
  res.json(cache.get(req.params.id));
});

This is the most common Node.js leak. Fix: use an LRU cache with a maximum size and a TTL (for example the lru-cache package), or an external cache like Redis.

WeakMap, WeakSet and WeakRef#

Weak collections hold references that don't prevent garbage collection. They're ideal for attaching data to objects you don't own.

JavaScript
const metadata = new WeakMap();

function tag(element, info) {
  metadata.set(element, info);   // when 'element' is collected, the entry disappears too
}
Map / SetWeakMap / WeakSet
KeysAny valueObjects only
Prevents GC of keysYesNo
Iterable / sizeYesNo
Use forGeneral dataPrivate data, caches tied to object lifetime

WeakRef and FinalizationRegistry give lower-level control, but GC timing is unpredictable, so use them sparingly and never for program logic.

Finding leaks with Chrome DevTools#

  1. Open DevTools → Memory tab.
  2. Take a heap snapshot (baseline).
  3. Perform the action you suspect leaks, for example open and close a modal 10 times.
  4. Click the trash-can icon to force GC, then take a second snapshot.
  5. Switch the view to Comparison and sort by "# Delta". Objects that keep growing are suspects.
  6. Select an object and read its Retainers panel: it shows the exact reference chain keeping it alive.
Quick checks

Filter snapshots by "Detached" to find detached DOM trees. The Performance tab with "Memory" checked shows a JS heap graph: a sawtooth that returns to the same baseline is healthy; a staircase that keeps climbing is a leak.

In Node.js#

Bash
node --inspect server.js        # then open chrome://inspect and use the Memory tab
node --heapsnapshot-signal=SIGUSR2 server.js   # kill -USR2 <pid> writes a snapshot
JavaScript
setInterval(() => {
  const { heapUsed } = process.memoryUsage();
  console.log(`heap: ${(heapUsed / 1024 / 1024).toFixed(1)} MB`);
}, 10_000);

Prevention checklist#

  • Every addEventListener, setInterval and subscription has a matching cleanup.
  • Use AbortController to group listener and fetch cleanup.
  • Give every cache a size limit or TTL.
  • Use WeakMap for data attached to objects you don't control.
  • Null out references to big objects when a long-lived module is done with them.
  • In React, return cleanup functions from useEffect.
Observers leak too

The observer pattern is a classic leak source: a subscriber that never unsubscribes stays alive as long as the subject does. Always return and call an unsubscribe function.

Heavy computation is a different performance problem from leaks. If your page freezes rather than bloats, see Web Workers in JavaScript.

Key takeaways#

  • JavaScript frees objects that are unreachable from roots, using mark-and-sweep and generational GC.
  • Leaks happen when references outlive their usefulness: globals, listeners, timers, closures, detached DOM and unbounded caches.
  • Clean up listeners and timers, ideally with AbortController and useEffect cleanups.
  • WeakMap and WeakSet attach data without keeping objects alive.
  • Find leaks by comparing heap snapshots and reading the retainers chain in DevTools.