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.
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#
Modern engines like V8 use a mark-and-sweep algorithm:
- Start from the roots: global variables, the current call stack, active closures and DOM nodes in the document.
- Mark every object reachable from a root by following references.
- Sweep: free every object that wasn't marked.
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 cyclesV8 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#
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#
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.
// 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 removed3. Timers that never stop#
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:
useEffect(() => {
const id = setInterval(fetchLatest, 5000);
return () => clearInterval(id);
}, []);4. Closures holding large data#
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#
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#
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.
const metadata = new WeakMap();
function tag(element, info) {
metadata.set(element, info); // when 'element' is collected, the entry disappears too
}| Map / Set | WeakMap / WeakSet | |
|---|---|---|
| Keys | Any value | Objects only |
| Prevents GC of keys | Yes | No |
Iterable / size | Yes | No |
| Use for | General data | Private 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#
- Open DevTools → Memory tab.
- Take a heap snapshot (baseline).
- Perform the action you suspect leaks, for example open and close a modal 10 times.
- Click the trash-can icon to force GC, then take a second snapshot.
- Switch the view to Comparison and sort by "# Delta". Objects that keep growing are suspects.
- Select an object and read its Retainers panel: it shows the exact reference chain keeping it alive.
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#
node --inspect server.js # then open chrome://inspect and use the Memory tab
node --heapsnapshot-signal=SIGUSR2 server.js # kill -USR2 <pid> writes a snapshotsetInterval(() => {
const { heapUsed } = process.memoryUsage();
console.log(`heap: ${(heapUsed / 1024 / 1024).toFixed(1)} MB`);
}, 10_000);Prevention checklist#
- Every
addEventListener,setIntervaland subscription has a matching cleanup. - Use
AbortControllerto group listener and fetch cleanup. - Give every cache a size limit or TTL.
- Use
WeakMapfor 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.
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
AbortControlleranduseEffectcleanups. WeakMapandWeakSetattach data without keeping objects alive.- Find leaks by comparing heap snapshots and reading the retainers chain in DevTools.