Skip to content
FrontDepth, Home

JavaScript Deep Dive

Memory leaks and garbage collection

How JavaScript decides what to free — reachability, roots, mark-and-sweep and V8's generations — why web apps still leak through listeners, timers, detached nodes and caches, and how to find leaks with heap snapshots.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

This topic starts at Junior level.

JuniorConcept

Reachability: what the garbage collector keeps

JavaScript has no free(). You allocate memory by creating objects, arrays, strings and closures, and the engine's reclaims it for you. Its rule is simple: an object is kept while it is reachable — while some chain of references leads to it from a root — and becomes garbage when no such chain is left.

Roots are the starting points the collector always treats as alive:

  • the global object (globalThis, window in a browser) and everything it holds;
  • local variables and arguments of the functions currently on the ;
  • references the host keeps on your behalf: DOM nodes in the document, registered event listeners, pending timers and promise callbacks, open connections.
JavaScript
let user = { name: "Ada", avatar: new Uint8Array(1_000_000) };
const session = { user };

user = null;

session.user = null;

user = null did not free anything: it removed one path, and the object was still reachable through session.user. Only after the second assignment does nothing lead to it, and the collector may free it. delete obj.key works the same way — it removes a reference, it does not release memory on the spot. When the collector actually runs is the engine's decision; page code cannot trigger it.

Cycles are not a problem

Old reference-counting collectors leaked cycles: two objects pointing at each other never reached a count of zero. Modern engines trace from the roots instead, so an isolated cycle is simply unreachable:

JavaScript
function link() {
  const a = {};
  const b = { a };
  a.b = b;
}

link();

After link() returns, a and b still reference each other, but nothing reaches them, so both can be collected. MDN states that no modern JavaScript engine uses reference counting for garbage collection any more — "circular references leak" is outdated advice for plain JavaScript objects.

Key points

  • Memory is freed by dropping references, never by "deleting" an object.
  • Reachable means "connected to a root", not "will be used again". An object you will never touch is still kept if something long-lived points at it.
  • That gap — reachable, but no longer needed — is exactly what a is.
JuniorConcept

What a leak is in a garbage-collected language

A in JavaScript is memory the program no longer needs but still references, so the collector has to keep it. The collector is not wrong: it cannot see your intent, only reachability.

Leaks rarely crash a page in a minute. They accumulate: each time the user opens a dialog, switches a view in a single-page app or receives a WebSocket message, a little more stays behind. Typical symptoms:

  • the JS heap grows with every repetition of an action and never returns to its baseline;
  • the app gets slower over a long session: more live objects to mark means longer and more frequent GC work on the ;
  • side effects repeat: duplicate requests, a handler that runs twice — the leaked code is often still working;
  • in the worst case the tab runs out of memory and the browser kills it.

Not every growth is a leak. A page that loads 50 MB of data and shows it uses a lot of memory, but it is not leaking. A leak is growth tied to repetition: do the same thing ten times and memory climbs ten steps.

JavaScript
const seen = [];

export function onMessage(message) {
  seen.push(message);
  render(message);
}

This module-level array is reachable for the lifetime of the page, so every message ever received stays in memory. A short test shows nothing; after a day of streaming it can hold hundreds of megabytes.

Memory and behaviour

A common real-world shape: a screen starts polling the server and never stops. Every time the user opens it, one more poller starts. After a long session the page sends requests many times more often than it should, and each old poller keeps the state of a component that is long gone. That combination is typical: a leak shows up both as memory and as behaviour.

The question to ask

For every long-lived reference, ask: who removes it, and when? If the answer is "nobody", you have found a leak candidate. The rest of this topic is about the usual answers to that question and how to confirm them.

JuniorPitfalls

Common sources: listeners, timers and globals

Most leaks in web apps follow one pattern: something long-lived (the window, the document, a global store, the browser's timer list) holds a reference to something short-lived (a dialog, a component, a request), and nobody removes it.

Forgotten event listeners

JavaScript
function openSearchDialog() {
  const results = new Array(10_000).fill(null);
  function onKeyDown(event) {
    if (event.key === "Escape") closeDialog(results);
  }
  document.addEventListener("keydown", onKeyDown);
}

Each call registers a new function, the document keeps all of them, and each listener's keeps its own results. Open the dialog ten times: ten listeners, ten arrays, ten Escape handlers firing at once. Remove the listener when the dialog closes, using the same function reference — removeEventListener with a freshly written arrow function removes nothing.

A listener on an element that is itself removed and forgotten is not a leak: the element and its listeners become unreachable together. The danger is listeners on targets that outlive the feature.

Timers that are never cleared

The browser references a setInterval callback until clearInterval, and a pending setTimeout until it fires. A polling loop built from a setTimeout that re-schedules itself lives forever unless something breaks the chain:

JavaScript
function startPolling(load) {
  let timer;
  let stopped = false;
  const tick = async () => {
    await load();
    if (!stopped) timer = setTimeout(tick, 5000);
  };
  tick();
  return () => {
    stopped = true;
    clearTimeout(timer);
  };
}

The stopped flag matters: the stop function may run while load() is in flight, and without the flag the next timer would be scheduled anyway.

Accidental globals

In sloppy-mode scripts, assigning to an undeclared name creates a property on the global object — a root:

JavaScript
function cacheResponse(data) {
  lastResponse = data;
}

lastResponse now lives as long as the page. ES modules and strict-mode code throw a ReferenceError instead, one more reason to write modules. Deliberate globals and module-level variables are roots too: whatever they hold lives for the whole session.

Logged objects

While DevTools is open, objects passed to console.log can be kept so that you can expand them later; heap snapshots even have a filter for objects retained by the console. Don't mistake that for a leak in your code, and don't ship code that logs large objects in a loop.

MiddleWeb platform

Mark-and-sweep and V8's generations

Every modern engine uses a tracing collector of the mark-and-sweep family:

  1. Mark. Start from the roots, follow every reference and mark each object reached.
  2. Sweep. Everything left unmarked is garbage; its memory goes back to free lists for new allocations.
  3. Compact (optional). Move surviving objects together so free memory is not split into small holes.

The algorithm is simple; the engineering is in running it without freezing the page. V8 (Chrome, Edge, Node.js, Deno) describes its collector, Orinoco, on the V8 blog. What follows is that description; the details change between versions.

The generational idea

The generational hypothesis says that most objects die young: temporary arrays, strings built in a loop, event objects, intermediate results. V8 therefore splits the heap:

  • Young generation. New objects are allocated here. It is small and collected often by the Scavenger (the minor GC). It is split into two semi-spaces: live objects are copied out of the full half into the empty one, and whatever is left behind is garbage by definition. The cost depends on the number of survivors, not on how much was allocated — which is why short-lived allocations are cheap. An object that survives one scavenge moves to the intermediate part of the young generation; one that survives a second scavenge is promoted to the old generation.
  • Old generation. Long-lived objects. It is collected by the major GC (mark-compact): marking the whole heap, sweeping, and compacting the most fragmented pages.

To collect only the young generation, V8 must know which old objects point to young ones. Write barriers record those pointers, and the scavenger treats them as extra roots.

Keeping pauses short

A stop-the-world collection of a large heap would block the for a long time. Orinoco combines three techniques: parallel (helper threads share the work during a pause), incremental (the work is split into small slices between JavaScript tasks) and concurrent (marking and sweeping run on background threads while JavaScript keeps running). Chrome can also give the collector idle time between frames.

Why this matters to you

  • Leaked objects survive every scavenge and end up in the old generation, where every major GC has to mark them again. Memory grows, and GC work grows with it.
  • An ever-growing heap means more frequent major collections. Most of that work is off the main thread, but not all of it, so on slow devices leaks often show up first as jank.

Page code cannot force a collection. Node.js exposes a gc() function with --expose-gc, and DevTools has a "Collect garbage" button: tools for measuring, not for production.

MiddlePitfalls

Detached DOM nodes, unbounded caches and captured data

Detached DOM nodes

A node removed from the document is detached. If JavaScript still references it, it cannot be collected — and because every node references its parent and its children (parentNode, childNodes), one reference keeps the whole detached tree reachable.

JavaScript
const rowsById = new Map();

function renderTable(items) {
  const table = document.createElement("table");
  for (const item of items) {
    const row = table.insertRow();
    row.insertCell().textContent = item.name;
    rowsById.set(item.id, row);
  }
  return table;
}

function showItems(container, items) {
  container.replaceChildren(renderTable(items));
}

showItems replaces the old table on the page, and ids that repeat get new rows in the map. But entries for items that are no longer shown are never deleted, and each of those old rows keeps its entire old table alive. Call rowsById.clear() before rendering, or reverse the lookup: a WeakMap from row to item lets rows go together with their table.

Unbounded caches

A Map used as a cache is a leak with good intentions: entries go in, nothing comes out.

JavaScript
const productCache = new Map();

function getProduct(id) {
  if (!productCache.has(id)) {
    productCache.set(id, fetch(`/api/products/${id}`).then((r) => r.json()));
  }
  return productCache.get(id);
}

Over a long session this map holds every product the user has ever seen. Every cache needs a policy:

  • a size limit — evict the least recently used entry. A Map iterates in insertion order, so deleting and re-inserting a key on each read gives you a small LRU;
  • a time to live — store a timestamp and drop stale entries;
  • a scope — clear it on logout or when the feature unmounts.

When the key is an object whose lifetime you don't control, a WeakMap drops the entry together with the key. And keep limits realistic: 10,000 large entries are bounded and still too much — check the retained size in a heap snapshot.

Closures holding large data

A keeps its environment reachable. Engines keep only the variables that closures actually use, so a long-lived callback should reference the small value it needs, not the large object it came from:

JavaScript
function attachDownload(button, report) {
  const { id } = report;
  button.addEventListener("click", () => downloadReport(id));
}

The click handler uses only id, so report is not kept for it. In V8, though, closures created in the same scope share one context: if another function in attachDownload used report, the handler would keep it alive too (see the closures topic). Keep heavy data out of scopes that create long-lived callbacks.

MiddleWeb platform

WeakMap, WeakSet, WeakRef and FinalizationRegistry

A normal reference keeps its target alive. A weak reference does not: it lets you attach data to an object without becoming a reason for that object to stay.

WeakMap and WeakSet

JavaScript
const metadata = new WeakMap();

function track(node) {
  metadata.set(node, { clicks: 0, firstSeen: performance.now() });
}

The map holds its keys weakly: once nothing else references node, the entry can be collected, value included. That makes it the right tool for "extra data about objects I don't own" — DOM nodes, objects from a library, request objects. A WeakSet does the same for membership ("have I already processed this object?").

The rules follow from what these collections must not reveal:

  • Keys must be objects or non-registered symbols. A string key like "user-1" can be created again at any time, so it can never be "gone". Registered symbols from Symbol.for() are rejected for the same reason.
  • No size, no iteration, no clear(). Listing the entries would let you observe when the collector ran, and engines must not expose that.

A WeakMap is not a cache for values. It holds keys weakly and values strongly, for as long as the key lives. A map from string ids to large objects needs a size limit, not a WeakMap. And a value that references its own key does not keep the key alive — WeakMap entries are ephemerons, not ordinary strong references.

WeakRef and FinalizationRegistry

JavaScript
const registry = new FinalizationRegistry((key) => {
  console.log("collected " + key);
});

function remember(report) {
  registry.register(report, report.id);
  return new WeakRef(report);
}

const ref = remember(loadReport());
const report = ref.deref();

deref() returns the target, or undefined once it has been collected. A target you have just created a WeakRef for, or just dereferenced, stays alive until the end of the current job, so it never disappears in the middle of synchronous code. FinalizationRegistry runs a callback some time after a registered object is collected, with the held value (report.id here), never the object itself.

Both have been Baseline (widely available) since April 2021, and MDN's advice is to avoid them where possible. The spec gives almost no guarantees: a target may never be collected, and a cleanup callback may run late or not at all — when the tab closes, for example. So never use a finalizer for something that must happen: removing listeners, clearing timers, closing sockets, saving data. Those need explicit cleanup. A finalizer is at most an optimisation, such as removing an emptied WeakRef from a cache map — and even then the callback must check that the entry was not replaced in the meantime.

SeniorFramework

Cleanup in components

In a single-page app a component mounts and unmounts many times, so whatever it starts on mount and forgets on unmount piles up:

JSX
function PricePanel({ symbol }) {
  const [quotes, setQuotes] = useState([]);
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    setInterval(async () => {
      setQuotes(await fetchQuotes(symbol));
    }, 5000);
    window.addEventListener("resize", () => setWidth(window.innerWidth));
  }, [symbol]);

  return <QuoteTable quotes={quotes} compact={width < 600} />;
}

Every mount, and every change of symbol, starts one more interval and adds one more resize listener, and nothing ever stops them. After N visits the page polls N times every five seconds, and each leaked interval keeps its closure — and with it the state setters of components that are long unmounted. In development, Strict Mode's extra setup + cleanup cycle makes it two pollers from the very first mount: a deliberate hint that the cleanup is missing.

The fix is a cleanup that undoes everything the setup started:

JSX
useEffect(() => {
  const controller = new AbortController();
  const { signal } = controller;

  const id = setInterval(async () => {
    try {
      const response = await fetch(`/api/quotes/${symbol}`, { signal });
      setQuotes(await response.json());
    } catch (error) {
      if (error.name !== "AbortError") console.error(error);
    }
  }, 5000);

  window.addEventListener("resize", () => setWidth(window.innerWidth), { signal });

  return () => {
    clearInterval(id);
    controller.abort();
  };
}, [symbol]);

One AbortController ties the lifetimes together. Calling abort() removes every listener registered with its signal — so the anonymous resize handler needs no saved reference — and cancels an in-flight fetch, which then rejects with an AbortError. Reading a response body that is still arriving is cancelled too, so a late response never reaches setQuotes.

Every subscription needs an owner

The same rule applies to everything a component subscribes to: store listeners, WebSockets, ResizeObserver and IntersectionObserver (disconnect()), media-query listeners, third-party widgets (destroy()). Most subscribe APIs return an unsubscribe function; returning it from the effect is the cleanup. For reading a value from an external store, useSyncExternalStore subscribes and unsubscribes for you.

To verify a fix like this, leave the screen and check that the number of intervals and global listeners is back to its baseline.

SeniorWeb platform

Finding leaks with Chrome DevTools

Don't guess — measure. A reliable workflow:

  1. Confirm the trend. In the Performance panel, turn on the Memory checkbox and record while you repeat the suspect action (open and close the dialog ten times). Click Collect garbage at the start and at the end. The JS heap, DOM node and listener counters should come back to a baseline; a staircase that never comes down is a leak. Chrome's Task Manager (More tools > Task manager, with the JavaScript memory column turned on) gives a quick live number.
  2. Take heap snapshots. In the Memory panel choose Heap snapshot. Taking a snapshot always starts with a garbage collection, so what you see is really reachable. Take three: a baseline, one after repeating the action several times, and one after undoing it (closing the view).
  3. Compare. The Comparison view shows, per constructor, how many objects were added and deleted between two snapshots and the change (the # Delta column). Repeat the action ten times and look for counts that grew by ten. In the Summary view, the filter Objects allocated between Snapshot 1 and Snapshot 2 answers a similar question.
  4. Follow the Retainers. Select a suspicious object: the Retainers pane shows the chain of references that keeps it alive, back towards a root. The leak is usually the first link you didn't expect — a Window listener, a timer, a module-level Map. Sort by Retained size (what would be freed together with the object), not Shallow size (the object's own size).
  5. Look for detached nodes. Type Detached in the class filter or pick Objects retained by detached nodes; recent Chrome versions also offer a Detached elements profile in the Memory panel.

Allocations on timeline records allocations over time: blue bars are objects still alive at the end of the recording, gray bars were collected. Blue bars that appear on every repetition point to the code that allocates the leaked objects. Allocation sampling attributes allocations to functions with little overhead, which suits long recordings.

performance.memory is not a leak detector

performance.memory (usedJSHeapSize, totalJSHeapSize, jsHeapSizeLimit) is non-standard, deprecated and available only in Chromium-based browsers, and MDN calls its numbers unreliable: pages can share a heap, while workers and cross-site iframes have their own. Its proposed replacement, performance.measureUserAgentSpecificMemory(), is experimental, not Baseline, and works only in a secure, cross-origin-isolated page. Use these for rough trends from the field, never as proof of a leak.

In Node.js the same tools are available: attach DevTools with --inspect, or write a snapshot from code with v8.writeHeapSnapshot() and open it in the Memory panel.

The platform's watchlist-leak incident lets you practise this workflow on a running app.

SeniorInterview tips

Interview tips

A 30-second answer. "JavaScript frees objects that are unreachable from the roots — globals, the call stack and what the host holds, like listeners and timers. A leak is memory that is still reachable but no longer needed: listeners on window, intervals nobody clears, detached DOM nodes, caches that only grow. I confirm a leak with heap snapshots and fix it by giving every subscription a cleanup."

Questions you are likely to get

  • How does garbage collection work in JavaScript? Reachability from roots, mark-and-sweep, and why cycles are not a problem. For senior roles add generations: the Scavenger for young objects, mark-compact for old ones, incremental and concurrent marking to keep pauses short.
  • Can a garbage-collected language leak? Yes. Give two concrete sources and their fixes.
  • Map or WeakMap? Weak keys, object (or non-registered symbol) keys only, no iteration or size — because collection must not be observable. Say when you would not use it: string keys, caches of values.
  • The app slows down after an hour. How do you investigate? Performance panel trend → three snapshots → Comparison → Retainers. Mention that Strict Mode's extra effect cycle in development exposes missing cleanups early.
  • Would you close connections in a FinalizationRegistry callback? No: the callback is not guaranteed to run.

Mistakes that cost points

  • "Setting a variable to null frees the memory." It removes one reference; the collector frees the object later, and only if nothing else reaches it.
  • "Circular references leak." Not with tracing collectors.
  • "Removed elements always leak their listeners." Only if something still references the element, or the listener sits on a target that outlives it.
  • Treating performance.memory or the Task Manager number as proof. Snapshot comparisons and retainer chains are the proof.

Senior signal

Talk about lifetimes, not only APIs: who owns each subscription, what bounds each cache, and how the team catches regressions — for example an end-to-end check that repeats a flow and asserts that intervals, listeners and DOM node counts return to their baseline.

JuniorReview checklist

What to check when reviewing code for memory leaks

Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. For each long-lived reference, ask who removes it and when; if nobody does, memory climbs with every repetition and old handlers keep running.

  • Does everything the setup starts have a matching stop? Each addEventListener on window or document, setInterval, self-rescheduling setTimeout, subscription or observer needs its removeEventListener, clearInterval, clearTimeout, unsubscribe or disconnect(). In React it goes in the effect's cleanup; Strict Mode's extra setup and cleanup in development exposes a missing one.
  • Is the listener removed with the same function reference? removeEventListener with a freshly written arrow function removes nothing. Expect a saved function, or { signal } with controller.abort().
  • Does a module-level array, Map or cache only grow? Ask for a policy: a size limit, a time to live or clearing on logout. A WeakMap fits only object keys.
  • Does the code keep references to removed DOM nodes? One reference in a variable or a Map keeps the whole detached tree alive.
  • Does a long-lived callback capture a large object for one field? A keeps what it references reachable; copy the small value first, for example const { id } = report.
  • Is required cleanup left to FinalizationRegistry? Its callback may run late or never, so listeners, timers and sockets need explicit cleanup.
  • Is the leak measured, not guessed? Repeat the action ten times and compare heap snapshots in the DevTools Memory panel: a constructor whose count grew by ten is a lead, and its Retainers show what keeps it alive.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Incident Simulator

Weekly Challenges