Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท JavaScript Performance

Finding and Fixing Memory Leaks

Learn how garbage collection works, the five most common leak patterns (listeners, timers, closures, detached DOM, caches) and how to find them in DevTools.

JavaScript manages memory for you with a garbage collector (GC). It frees objects that nothing can reach any more. A memory leak happens when your code keeps a reference to something you no longer need, so the collector cannot free it. A page that leaks gets slower and slower, may stutter during GC pauses, and eventually crashes a tab, which hurts long-lived apps such as dashboards, single-page apps and web email most.

How garbage collection decides

The collector starts from roots (the global object, the current call stack) and follows every reference. Whatever it can reach is alive. Anything else is garbage.

flowchart LR
  Root["Roots<br/>window, stack"] --> A["App state"]
  A --> B["User list"]
  Root --> C["Event listener"]
  C --> D["Closure holding a big array"]
  X["Old object<br/>(unreachable)"] -.-> Y["Collected"]

Objects reachable from a root stay in memory, even if you will never use them again.

A leak is therefore always "something still points at it". Finding the leak means finding the pointer.

Leak 1: forgotten event listeners

Adding a listener creates a reference from the target to your function, and the function keeps its closure alive. If the target outlives the component, the listener leaks:

JavaScript
function mountWidget(element) {
  const bigData = new Array(1_000_000).fill("x");
  window.addEventListener("resize", () => {
    console.log(bigData.length, element.id);
  });
}
// If the widget is removed, the window listener (and bigData and element) stay.

Fix: remove the listener on teardown, or tie it to an AbortController:

JavaScript
function mountWidget(element) {
  const controller = new AbortController();
  window.addEventListener("resize", onResize, { signal: controller.signal });
  return () => controller.abort(); // call when the widget is removed
}

Leak 2: timers and intervals

A running setInterval keeps its callback and everything it captured alive until you call clearInterval. Always store the id and clear it when the owner goes away.

Leak 3: growing caches and collections

A Map or object used as a cache grows forever if you never evict. Use limits (LRU), or hold keys weakly with WeakMap and WeakSet, which let the collector remove an entry when the key object is otherwise unreachable.

JS Map versus WeakMap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A simple bounded cache is often enough:

JS A tiny LRU cache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Leak 4: detached DOM nodes

If you remove an element from the page but still keep a variable (or listener, or array entry) pointing to it, the element and its whole subtree stay in memory. These are called detached DOM trees.

JavaScript
const rows = [];
function addRow() {
  const row = document.createElement("tr");
  table.append(row);
  rows.push(row);          // keeps every row alive...
}
function clearTable() {
  table.innerHTML = "";    // ...even after the table is emptied
}

Fix: also clear rows.length = 0, or do not keep the references at all.

Leak 5: closures that capture too much

A closure keeps the whole scope alive in some engines. A small callback created next to a huge object can retain it. Keep large data in narrow scopes, and set variables to null when a long-lived function no longer needs them.

Finding leaks with DevTools

  1. Open the Memory panel and choose Heap snapshot.
  2. Perform the suspect action (open and close a dialog) several times, forcing GC with the trash-can button.
  3. Take a second snapshot and use the Comparison view: look for objects whose count grows by exactly the number of repetitions.
  4. Check Detached elements, and read the Retainers panel to see what still points at an object.

The Performance panel with the Memory checkbox shows a "sawtooth" graph for healthy code, where memory rises and drops after each GC. A leak looks like a staircase that never drops back.

You can also watch memory in code during testing (Chromium only):

JavaScript
if (performance.memory) {
  console.log(Math.round(performance.memory.usedJSHeapSize / 1048576), "MB used");
}

performance.measureUserAgentSpecificMemory() is the more accurate, standards-track alternative and requires cross-origin isolation.

Prevention checklist

  • Pair every addEventListener, setInterval, observe() and subscription with a cleanup.
  • Use AbortController, WeakMap, WeakRef and bounded caches.
  • In frameworks, use the teardown hooks (onUnmounted, useEffect cleanup, ngOnDestroy).
  • Test long sessions: repeat navigation 50 times and watch memory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a memory leak in JavaScript?

    The collector frees only unreachable objects, so any stray reference prevents cleanup.
  2. 2. Which API ties the removal of several listeners to one call?

    Passing the same signal to addEventListener lets one abort() remove them all.
  3. 3. Why can a WeakMap help avoid leaks?

    A WeakMap does not keep its key objects alive.
  4. 4. In a heap snapshot comparison, what pattern suggests a leak?

    Repeating an action 10 times and seeing 10 extra objects is the classic signature.

Summary

  • The GC frees only unreachable objects; leaks are unwanted references.
  • Common causes: listeners, timers, unbounded caches, detached DOM nodes and large closures.
  • Clean up everything you start, bound your caches and use weak references where fitting.
  • Find leaks with heap snapshot comparison and the Retainers view.

Next: The Critical Rendering Path