Difficulty: Advanced
What causes memory leaks in JavaScript applications, and how do you detect and fix them in the browser and in Node.js?
A memory leak in JavaScript is memory that your program no longer needs but that the garbage collector cannot free because something still references it. JavaScript engines use reachability-based (mark-and-sweep) garbage collection, so a leak is almost always an unintended reference from a live root, such as a global variable, an active timer, an event listener, a closure or a long-lived cache. You find leaks with heap snapshots and allocation timelines in Chrome DevTools or the Node.js inspector, and fix them by removing the reference at the right lifecycle moment.
V8 starts from roots (the global object, the current call stack, active handles like timers and sockets) and marks everything reachable from them. Anything unmarked is swept. Circular references alone do not leak: two objects pointing at each other but unreachable from a root are collected. So the question is always "which root is still holding this?"
window.addEventListener('resize', handler) and never removes it. The handler's closure keeps the component's data alive after it unmounts.setInterval callbacks run forever unless cleared, along with everything they close over.window. ES modules and strict mode turn this into a ReferenceError.Map of session data or memoized results that only grows. Common in Node.js servers that run for weeks.--inspect and use Chrome DevTools, log process.memoryUsage().heapUsed, write snapshots with v8.writeHeapSnapshot(), or use --heapsnapshot-near-heap-limit. A process that grows until "JavaScript heap out of memory" is the classic sign.| Leak source | Fix |
|---|---|
| Event listeners | removeEventListener in cleanup, or pass { signal } from an AbortController and call abort() |
| Timers | clearInterval / clearTimeout in cleanup (React useEffect return) |
| Detached DOM | Null out references, or store element metadata in a WeakMap |
| Caches | LRU with a max size, TTLs, or WeakMap keyed by objects |
| Subscriptions | Always keep and call the unsubscribe function |
In React, the useEffect cleanup function is where nearly all of these fixes go.
// Leaky: listener and interval outlive the widget
function mountPriceTickerLeaky(el) {
const history = new Array(100_000).fill(0); // big closure data
window.addEventListener('resize', () => el.style.width = `${history.length}px`);
setInterval(() => { el.textContent = `Rs ${Math.random().toFixed(2)}`; }, 1000);
}
// Fixed: one AbortController removes every listener; return a cleanup
function mountPriceTicker(el) {
const controller = new AbortController();
const { signal } = controller;
window.addEventListener('resize', () => { /* resize logic */ }, { signal });
el.addEventListener('click', () => { /* open details */ }, { signal });
const timer = setInterval(() => { el.textContent = 'tick'; }, 1000);
return function unmount() {
controller.abort(); // removes both listeners
clearInterval(timer); // stops the timer and frees its closure
};
}
// React equivalent
// useEffect(() => mountPriceTicker(ref.current), []);
Passing an AbortSignal to addEventListener lets you remove many listeners with one abort() call. Returning a cleanup function matches how React's useEffect expects teardown to work.
// Detached DOM: removed from the page but still referenced
const removedRows = [];
function deleteRow(row) {
row.remove();
removedRows.push(row); // leak: whole subtree stays in memory
}
// Fix: do not keep the node, or store metadata in a WeakMap keyed by it
const rowMeta = new WeakMap();
// Node.js: a per-request cache that only grows
const sessions = new Map();
function onRequest(req) {
sessions.set(req.id, { body: req.body, at: Date.now() }); // never deleted
}
// Fix: evict on a schedule (or use an LRU / Redis with TTL)
const TTL_MS = 15 * 60 * 1000;
setInterval(() => {
const now = Date.now();
for (const [id, s] of sessions) if (now - s.at > TTL_MS) sessions.delete(id);
}, 60_000).unref(); // unref so the timer does not keep the process alive
setInterval(() => {
const { heapUsed } = process.memoryUsage();
console.log('heapUsed MB', (heapUsed / 1024 / 1024).toFixed(1));
}, 30_000).unref();
Arrays and Maps that hold DOM nodes or request data are the most common real leaks. Bounded eviction and logging heapUsed over time make growth visible before the process crashes.
Memory Leak, Garbage Collection, Mark-and-Sweep, Detached DOM, Event Listeners, Heap Snapshot