Sub topic 7
Common Memory Leaks and How to Fix Them
This chapter assumes you know how reachability from roots decides what the collector keeps, and how closures retain the variables they use. You should also be comfortable with timers, event listeners, and basic DOM APIs.
A memory leak in JavaScript is memory your program no longer needs but that is still reachable. The collector works correctly here. Your code holds a reference it forgot about, so the collector cannot free the memory. Most leaks follow a few repeatable patterns.
How a leak forms
The component is gone, but the chain from a root to the large array still exists. Every leak fix comes down to breaking one link in a chain like this.
Forgotten timers
An active setInterval is referenced by the host environment. Its callback, and everything the callback closes over, stays alive until you clear the timer.
function startPolling(state) {
const intervalId = setInterval(() => {
console.log("items:", state.items.length);
}, 1000);
return () => clearInterval(intervalId);
}
const stop = startPolling({ items: new Array(100_000).fill(0) });
// Later, on teardown:
stop();Have every function that starts a timer return a matching cleanup function.
Forgotten event listeners
A listener on a long-lived target such as window or document keeps its handler reachable. Pass an AbortSignal so a single call removes all the listeners tied to one component:
function mount() {
const controller = new AbortController();
const { signal } = controller;
window.addEventListener("resize", () => console.log(innerWidth), { signal });
document.addEventListener("keydown", (e) => console.log(e.key), { signal });
return () => controller.abort();
}
const unmount = mount();
unmount(); // removes both listenersDetached DOM nodes
A node that has been removed from the document is "detached". It stays in memory if JavaScript still references it, and it also keeps its whole subtree alive.
const cache = { panel: document.createElement("div") };
document.body.appendChild(cache.panel);
cache.panel.remove(); // removed from the page, still reachable via cache
cache.panel = null; // now collectableUnbounded caches
A Map or plain object used as a cache grows forever unless something evicts entries. Set a size limit:
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);
this.map.set(key, value); // mark as most recently used
return value;
}
set(key, value) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.limit) {
this.map.delete(this.map.keys().next().value); // evict oldest
}
}
}
const cache = new LRUCache(2);
cache.set("a", 1);
cache.set("b", 2);
cache.set("c", 3);
console.log(cache.get("a")); // undefinedIf the cache keys are objects and an entry should disappear along with its key, a WeakMap may suit better. The next chapter covers it.
Closures and accidental globals
A long-lived closure keeps alive every variable it uses. Copy out only the values you need before creating the closure. Assigning to an undeclared variable in sloppy mode creates a property on the global object, which is a root. Modules and "use strict" turn that mistake into a ReferenceError.
Summary of fixes
| Leak pattern | Link that retains memory | Fix |
|---|---|---|
| Timer | Host timer list → callback | `clearInterval` / `clearTimeout` |
| Listener | Event target → handler | `removeEventListener` or `AbortSignal` |
| Detached DOM | JS variable → removed node | Null the reference |
| Cache | Map → entries | Size limit or `WeakMap` |
| Accidental global | Global object → value | Strict mode, modules |
Exercise
A modal component adds a keydown listener to document each time it opens and never removes it. After opening and closing it 50 times, what is retained, and what is the simplest fix?
Show answer
Fifty handlers stay attached to document, along with everything each handler closes over, such as the modal's state and DOM nodes. Create an AbortController when the modal opens, pass its signal to addEventListener, and call controller.abort() when the modal closes.
Exercise
Why does cache.panel.remove() alone not free the panel's memory?
Show answer
remove() detaches the node from the document, but the cache object still references it, so the node stays reachable from a root. Setting cache.panel = null breaks that last link.