Sub topic 7
Common Memory Leaks and How to Fix Them
This chapter assumes you know how reachability from roots decides what the garbage collector keeps, how mark-and-sweep works, and how closures retain the variables they use. You should also be comfortable with timers, event listeners, and basic DOM manipulation.
A memory leak in JavaScript is rarely memory the engine "forgot" to free. The collector does its job correctly. A leak is memory your program no longer needs that is still reachable from a root, so the collector is not allowed to free it. Every fix in this chapter comes down to cutting the reference path you forgot about.
The Shape of a Leak
Most leaks follow the same pattern. A long-lived object, such as window, a module-level variable, a timer queue, or a DOM node that stays on the page, holds a reference to a short-lived object. The short-lived object should have died when its component, request, or page view ended. Instead, it lives as long as its holder.
To diagnose a leak, ask two questions:
- What object is still in memory that should not be?
- What chain of references connects it to a root?
Heap snapshots, covered in a later chapter, answer the second question directly with their "retainers" view. The patterns below are the chains you will see most often.
Accidental Globals
In sloppy (non-strict) mode, assigning to an undeclared variable creates a property on the global object. Global properties are reachable for the life of the page or process.
function processRows(rows) {
results = rows.map((r) => r * 2); // missing let/const: creates globalThis.results
return results.length;
}
processRows(new Array(100000).fill(1));
console.log(typeof globalThis.results); // "object": the array is now permanentThe same thing happens with this inside a plain function called without a receiver in sloppy mode, because this is the global object.
Fix: use strict mode. ES modules and class bodies are strict automatically, and in strict mode the assignment above throws a ReferenceError instead of leaking. Linters such as ESLint's no-undef rule catch it before runtime.
"use strict";
function processRows(rows) {
const results = rows.map((r) => r * 2);
return results.length;
}
console.log(processRows([1, 2, 3])); // 3Intentional globals and module-level variables also leak if they grow without bound. A module-level array that collects every request is a global in practice.
Forgotten Timers and Intervals
The runtime keeps a reference to each active timer's callback. An interval that is never cleared keeps its callback, and everything the callback closes over, alive forever.
function startPolling(widget) {
const history = [];
setInterval(() => {
history.push({ time: Date.now(), value: widget.read() });
}, 1000);
}This code has two problems. widget can never be collected, even after the UI removes it. history also grows by one entry per second without limit. The leak is both retained and growing, which is the most dangerous kind.
Fix: keep the timer ID and clear it when the owner is torn down. Expose a cleanup function so callers cannot forget to do it.
function startPolling(widget) {
const history = [];
const id = setInterval(() => {
history.push({ time: Date.now(), value: widget.read() });
if (history.length > 100) history.shift(); // bound the growth too
}, 1000);
return function stopPolling() {
clearInterval(id);
};
}
const widget = { read: () => Math.random() };
const stop = startPolling(widget);
setTimeout(stop, 5000); // stop after 5 seconds; the process can now exitA setTimeout that has already fired no longer holds its callback, so one-shot timers leak only while they are pending. A long pending delay or a timeout that reschedules itself recursively behaves like an interval.
Event Listeners That Outlive Their Owners
An event target keeps a reference to every listener registered on it. When the target is long-lived, like window, document, a WebSocket, or a Node.js EventEmitter, each listener and its closure stays reachable until it is removed.
class Tooltip {
constructor(text) {
this.text = text;
this.cache = new Array(50000).fill(text);
window.addEventListener("scroll", () => this.reposition());
}
reposition() {
/* ... */
}
}Each Tooltip you create and "destroy" stays alive, because the arrow function captures this and window holds the arrow function. Calling removeEventListener would not help here, since you need the exact same function reference to remove it and the code never saved one.
Fix: store the handler or, more simply, use an AbortController and pass its signal. One abort() call removes every listener registered with that signal.
class Tooltip {
constructor(text) {
this.text = text;
this.controller = new AbortController();
const { signal } = this.controller;
window.addEventListener("scroll", () => this.reposition(), { signal });
window.addEventListener("resize", () => this.reposition(), { signal });
}
reposition() {
/* ... */
}
destroy() {
this.controller.abort(); // removes both listeners
}
}In Node.js, EventEmitter prints a MaxListenersExceededWarning when more than 10 listeners are added for one event. Treat that warning as a leak report, and do not just raise the limit. Remove listeners with emitter.off(event, fn) or use events.once.
Closures Retaining More Than You Expect
A closure keeps alive the variables it references. Engines like V8 also share one context object among all closures created in the same scope. If any closure in that scope uses a large variable, every closure created there keeps that variable alive.
function setup() {
const huge = new Array(1_000_000).fill("x");
function logSize() {
console.log(huge.length); // uses huge
}
logSize();
return function onClick() {
console.log("clicked"); // does not use huge
};
}
const handler = setup();
// In V8, huge may still be retained: onClick shares the scope context with logSize.Fix: pull only what you need out of the large value before creating long-lived closures, and drop the reference when you are done.
function setup() {
let huge = new Array(1_000_000).fill("x");
const size = huge.length; // keep only the small value
huge = null; // release the big one
return function onClick() {
console.log("clicked, size was", size);
};
}
const handler = setup();
handler();Detached DOM Nodes
A detached DOM node has been removed from the document but is still referenced from JavaScript. The node stays in memory, and so does its whole subtree, because a child node references its parent and the parent references all of its children. Keeping one <td> can keep an entire table alive.
const rows = [];
function renderList(container, items) {
for (const item of items) {
const li = document.createElement("li");
li.textContent = item;
container.appendChild(li);
rows.push(li); // module-level array keeps every <li>
}
}
function clearList(container) {
container.replaceChildren(); // removed from the page, still in rows
}Fix: clear your own references when you remove nodes, or avoid storing nodes long-term. Query them when needed, or key side data with a WeakMap, which the next chapter covers.
function clearList(container) {
container.replaceChildren();
rows.length = 0; // drop JavaScript references too
}Chrome DevTools heap snapshots let you filter for "Detached" to find these nodes directly.
Unbounded Caches and Collections
Memoization caches, request deduplication maps, and "seen IDs" sets are useful until they grow forever. A Map keyed by user ID or URL in a long-running server never shrinks unless you remove entries.
const cache = new Map();
function getReport(id) {
if (!cache.has(id)) cache.set(id, buildReport(id));
return cache.get(id);
}Fix: bound the cache by size or time. A Map iterates in insertion order, which makes a simple LRU (least recently used) cache short to write.
class LRUCache {
constructor(limit) {
this.limit = limit;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return undefined;
const value = this.map.get(key);
this.map.delete(key); // move to the most-recent position
this.map.set(key, value);
return value;
}
set(key, value) {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.limit) {
const oldestKey = this.map.keys().next().value;
this.map.delete(oldestKey);
}
}
}
const cache = new LRUCache(2);
cache.set("a", 1);
cache.set("b", 2);
cache.get("a");
cache.set("c", 3); // evicts "b"
console.log([...cache.map.keys()]); // [ 'a', 'c' ]If the cache key is an object and the entry should die with that object, a WeakMap is the right tool instead of a size limit.
Less Obvious Retainers
Some leaks only show up in particular environments:
| Retainer | Why it leaks | Fix |
|---|---|---|
| `console.log(obj)` with DevTools open | The console keeps logged objects so you can inspect them | Remove debug logging from hot paths |
| Unsettled promises | Pending promises keep their `then` callbacks and captured scope | Add timeouts or abort signals to long waits |
| Observers (`MutationObserver`, `ResizeObserver`, `IntersectionObserver`) | The observer keeps its callback and observed targets | Call `disconnect()` on teardown |
| Third-party subscriptions (stores, sockets, pub/sub) | The publisher holds your callback | Call the unsubscribe function the library returns |
| Node.js `require` cache and module state | Modules are singletons for the life of the process | Avoid growing module-level collections |
A Teardown Checklist
When you build anything with a lifecycle, such as a component, connection, or job, pair every acquisition with a release:
setInterval/setTimeout→clearInterval/clearTimeoutaddEventListener→AbortController.abort()orremoveEventListenerwith the same functionobserver.observe→observer.disconnect()subscribe→ the returned unsubscribe function- Stored DOM nodes → set to
nullor empty the array - Cache insertions → an eviction policy
Exercise
A single-page app creates a Chart object each time the user opens a dashboard tab. The constructor calls window.addEventListener("resize", () => this.redraw()) and setInterval(() => this.fetchData(), 5000). After switching tabs 30 times, memory has grown steadily. Name both retaining paths and write a destroy() method that cuts them.
Show answer
window holds the resize arrow function, which captures this (the Chart). The timer queue holds the interval callback, which also captures this. Fix: in the constructor, create this.controller = new AbortController() and pass { signal: this.controller.signal } to addEventListener, then store this.intervalId = setInterval(...). Then define destroy() { this.controller.abort(); clearInterval(this.intervalId); } and call it when the tab closes.
Exercise
Why does keeping a reference to one removed <span> from a large detached table keep the whole table in memory?
Show answer
DOM nodes reference each other in both directions. The span's parentNode leads up to the table, and the table references all its rows and cells. Since the span is reachable from JavaScript, the entire connected tree is reachable, and none of it can be collected.
Exercise
A Node.js server memoizes results in const results = new Map() keyed by request query strings. Memory grows for days until the process crashes. Give two different fixes and say when each fits.
Show answer
Use a bounded LRU cache (size limit with eviction) or a time-based expiry when keys are strings or other primitives, because a WeakMap cannot hold primitive keys. Use a WeakMap when the key is an object whose lifetime should decide the entry's lifetime. Removing the cache entirely also works if it does not measurably help performance.