What are memory leaks?

A memory leak is memory your program no longer needs but that cannot be freed, because something still references it; in JavaScript that means an unintended reference keeps objects reachable, so the garbage collector cannot reclaim them and memory grows over time.

Common causes in front-end code

  • Event listeners not removed, especially on window/document from components that mount and unmount.
  • Timers and intervals that are never cleared and capture large data in their closures.
  • Detached DOM nodes: elements removed from the page but still referenced from JavaScript (in an array, a cache, or a closure).
  • Unbounded caches: a Map or object used as a cache that only ever grows.
  • Subscriptions (WebSocket handlers, observables, store subscriptions) without unsubscribe.
  • Accidental globals (assigning to undeclared variables in sloppy mode).
  • Closures holding on to big objects longer than intended.

Symptoms

The page gets slower over time, memory in Task Manager keeps rising, and the app may eventually crash, especially in long-lived SPAs and dashboards.

Prevention

  • Clean up in the same place you set up: React's effect cleanup, AbortController signals for listeners, clearInterval, unsubscribe().
  • Bound your caches (LRU with a maximum size) or use WeakMap when keyed by objects.
  • Avoid storing DOM nodes long-term; store ids and look nodes up when needed.

Finding leaks

Chrome DevTools → Memory → take heap snapshots before and after repeating an action several times, compare them, and look for growing object counts and "Detached" DOM trees. The retainers view shows exactly what keeps an object alive.

Code example

js
1// LEAK: a listener on a long-lived target captures a big object and is never removed
2function leakyWidget(target) {
3 const bigData = new Array(100_000).fill("data");
4 target.addEventListener("tick", () => bigData.length); // bigData lives as long as target
5}
6
7// FIX: give every setup a teardown
8function widget(target) {
9 const bigData = new Array(100_000).fill("data");
10 const controller = new AbortController();
11 target.addEventListener("tick", () => bigData.length, { signal: controller.signal });
12 const timer = setInterval(() => bigData.length, 1_000);
13 return function destroy() {
14 controller.abort(); // removes the listener
15 clearInterval(timer); // stops the timer
16 };
17}
18
19const bus = new EventTarget(); // stands in for window/document
20const destroy = widget(bus);
21destroy(); // nothing references bigData any more -> collectable
22
23// LEAK: an unbounded cache. FIX: cap its size (simple LRU using Map insertion order)
24class BoundedCache {
25 #map = new Map();
26 constructor(max = 100) {
27 this.max = max;
28 }
29 get(key) {
30 if (!this.#map.has(key)) return undefined;
31 const value = this.#map.get(key);
32 this.#map.delete(key);
33 this.#map.set(key, value); // mark as recently used
34 return value;
35 }
36 set(key, value) {
37 this.#map.delete(key);
38 this.#map.set(key, value);
39 if (this.#map.size > this.max) this.#map.delete(this.#map.keys().next().value); // evict oldest
40 }
41 get size() {
42 return this.#map.size;
43 }
44}
45const cache = new BoundedCache(3);
46for (let i = 0; i < 10; i++) cache.set(i, `value ${i}`);
47console.log(cache.size); // 3 - never grows without limit

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app