Memory Leaks
Memory leaks silently grow your app's memory usage until it crashes or slows to a crawl. Learn the six classic leak patterns, how to detect them with DevTools heap snapshots, and the fixes that prevent them for good.
What causes memory leaks in JavaScript?
A memory leak happens when your code keeps references to data it no longer needs, so the garbage collector can't free it. Common causes are event listeners and intervals that are never removed, growing caches or arrays, references to removed DOM elements, and closures holding large objects. Find them with the DevTools Memory panel by comparing heap snapshots.
const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
const id = setInterval(poll, 5000);
// cleanup (e.g. when a component unmounts)
controller.abort();
clearInterval(id);The 6 Classic Leak Patterns
Accidental globals
Assigning to undeclared variable creates window property that never dies
Fix: Use 'use strict' and always declare with let/const/var
Forgotten event listeners
Listener closure holds reference to element/data after removal
Fix: Always removeEventListener on cleanup (or use AbortSignal)
Detached DOM nodes
Element removed from DOM but still referenced in JS array/map
Fix: Remove JS references when removing DOM nodes, or use WeakRef
Closure over large data
Inner function captures big object in its scope
Fix: Extract only the values you need before creating the closure
Uncleaned timers
setInterval keeps firing, holding references to component/data
Fix: clearInterval/clearTimeout in cleanup functions
Unbounded caches
Map/array grows indefinitely caching items that should expire
Fix: Use WeakMap for object-keyed caches, or LRU cache with max size
Weak References — The GC-friendly Collections
WeakMap
WeakSet
WeakRef
Common Pitfalls
Interactive Demo
Code Editor
<button id="start">Start widget</button>
<button id="stop">Stop widget (cleanup)</button>
<p id="out">Ticks: 0</p>Preview
Memory Leaks — step by step
Forgotten Event Listeners
Adding event listeners without removing them when a component or element is destroyed is a classic leak. The listener holds a reference to its callback, preventing garbage collection of the associated scope.
🎯 Quick Check
Which pattern most commonly causes a memory leak in event-driven UI code?
JavaScript Memory Leaks: summary
Key points
- Remove listeners and clear timers in cleanup functions (React
useEffectreturn, componentdestroy). - Use
WeakMaporWeakReffor caches keyed by objects that may go away. - Detached DOM nodes still referenced from JavaScript stay in memory.
Frequently asked questions
›How do I find a memory leak in Chrome?
Open DevTools → Memory, take a heap snapshot, repeat the suspicious action several times, take another snapshot, and compare them to see which objects keep growing.