Concept Explanation
Imagine you go to a restaurant. You eat (use memory) and leave the plate on the table. In JavaScript, the Garbage Collector is the busboy who comes by to take your plate away once you've finished.
A Memory Leak happens when you keep holding your plate even after you're done eating. The table gets full, No one else can eat, and the restaurant (your app) crashes.
The rule the collector follows is simple and worth internalising: an object survives as long as it is reachable from a root. Roots are the global object, the current call stack, and anything they point to. The collector does not care whether you still need the object. It only asks whether anything still points at it. Every leak in JavaScript is therefore one bug wearing different costumes: a reference you forgot to drop.
Long-lived single-page apps are where this hurts. A page you reload every few minutes forgives everything. A dashboard left open for eight hours does not.
Common Leaks
- Global Variables: Variables attached to
windownever get cleared. - Forgotten Timers: An
setIntervalthat runs in the background even after the page is closed. - Closures: Holding a reference to a giant object inside a tiny inner function.
- Detached DOM nodes: You removed the element from the page, but a JS array or a Map still holds it, so the node and its entire subtree stay in memory.
- Un-removed listeners:
addEventListeneronwindowfrom inside a component that unmounts a hundred times.
Syntax or Core Structure
The leak and the fix
// LEAKS: the interval keeps 'rows' alive forever
function startPolling(rows) {
setInterval(() => render(rows), 1000);
}
// FIXED: hand back a teardown and actually call it
function startPolling(rows) {
const id = setInterval(() => render(rows), 1000);
return () => clearInterval(id);
}
const stop = startPolling(rows);
// later...
stop();
Detached nodes
const cache = [];
function addRow() {
const li = document.createElement('li');
cache.push(li); // <-- the reference that keeps it alive
list.appendChild(li);
}
list.innerHTML = ''; // removed from the DOM, still in 'cache'
WeakMap: references that do not count
const meta = new WeakMap();
meta.set(element, { clicks: 0 });
// When 'element' is removed and nothing else points to it,
// the entry disappears on its own. A plain Map would pin it forever.
Real World Example
The dashboard that died at lunchtime. A trading dashboard subscribed to a WebSocket on mount and never unsubscribed. Each route change added a new subscription plus a closure over the previous chart data. After roughly three hours of a trader clicking between tabs, the tab was holding over a gigabyte and Chrome killed it. The diagnosis took one heap snapshot: the retainer path pointed straight at an array of stale handlers. The fix was four lines of cleanup.
How to Find One
- Open DevTools, Memory panel, and record an Allocation instrumentation on timeline.
- Perform the suspect action ten times: open a modal, close it, repeat.
- Force garbage collection, then take a heap snapshot.
- Take a second snapshot after ten more repetitions and use Comparison view.
- Anything whose count grows monotonically is your leak. Click it and read the Retainers panel; that path names the reference you forgot to release.
Common Mistakes
- Assuming
null-ing one variable frees the object. If anything else still references it, nothing happens. - Cleaning up listeners but not timers, or the reverse. Audit both together.
- Using a
Mapkeyed by DOM node for caching. UseWeakMapunless you genuinely want to keep the node alive. - Reading a single memory number and panicking. Heap size sawtooths by design; only a rising floor across collections indicates a leak.
- Forgetting
AbortController. It is the tidiest way to cancel a fetch and detach many listeners at once.
Best Practices
- Write the teardown in the same commit as the setup. In React, that is the effect's return value; in a Web Component,
disconnectedCallback. - Prefer
AbortControllerand pass its signal toaddEventListenerandfetch, so oneabort()cleans up everything. - Use
WeakMapandWeakSetfor metadata keyed on objects you do not own. - Cap every cache. An unbounded cache is a leak with good intentions.
- Add a soak test: script the app through its main flows a few hundred times and assert the heap does not grow without bound.
Practice Exercises
- The Leak Hunter: Open Chrome DevTools, go to the "Memory" tab, and take a "Heap Snapshot." Try to find an object you recently created.
- The Timer Trap: Write a script that intentionality leaks memory by creating 1,000 objects every second inside an interval that never stops.
- The WeakMap: Research
WeakMapand explain how it helps prevent memory leaks compared to a regularMap.