الانتقال إلى المحتوى
FrontendJavaScript· 7 دقائق للقراءة

Garbage Collection Doesn't Prevent Memory Leaks

The collector frees what's unreachable, not what's unused, so a forgotten reference keeps memory alive.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • ES2025
محتويات المقال

Analysts keep a trading dashboard open all day, opening and closing chart panels. By the afternoon the tab is sluggish, and some days it crashes; a reload always "fixes" it. A heap snapshot tells the story: only one chart is on screen, yet hundreds of PriceChart objects are alive, each with its full array of price samples. Every chart that was ever closed is still in memory, and the code has a garbage collector the whole time.

The common misconception

The belief: JavaScript has a garbage collector, so memory leaks can't happen. Leaks are what you get in C, when you forget to call free().

There's real truth in it. You never free memory by hand in JavaScript, and the classic leak of manual memory management, an object nothing points to that nobody released, is exactly what a collector cleans up. Even reference cycles are fine: MDN notes that all modern engines use a collector, which doesn't care whether unreachable objects point at each other. And most pages are short-lived: you navigate away, the whole heap goes, and a slow leak never gets the chance to show. The half-truth hides a second kind of leak that no collector can see.

What actually happens

The collector frees what's unreachable, not what's unused

MDN explains the trade-off. Knowing whether a piece of memory is still needed is undecidable in general, so collectors settle for an approximation: "no longer needed" becomes "unreachable". Starting from the roots (in JavaScript, the global object), the collector marks every object it can reach by following references, then frees the rest. If your code can still reach an object, even through a path you've forgotten about, it stays.

A JavaScript leak is a reference you forgot

Chrome's DevTools documentation defines a as a bug that makes the page use more and more memory over time. In a garbage-collected language that bug is almost always a long-lived object holding a reference to a short-lived one. The usual long-lived holders are window and document (their listeners), setInterval callbacks, module-level Maps and arrays used as caches, and anything those reach in turn.

The chart that never left

Here's the dashboard's chart, reduced to the part that matters. destroy() removes the canvas from the page and looks complete, but the constructor did two things and destroy() only undid one of them:

JavaScript price-chart.js
class PriceChart {  points = Array.from({ length: 100_000 }, () => Math.random());  constructor(container) {    this.el = document.createElement("canvas");    container.append(this.el);    window.addEventListener("resize", () => this.redraw());  }  redraw() {    console.log(`redraw ${this.points.length} points`);  }  destroy() {    this.el.remove(); // the canvas leaves the page, the listener stays  }}const app = document.querySelector("#app");for (let i = 0; i < 200; i++) new PriceChart(app).destroy();

Follow the references in the wrong version: window keeps its resize listeners, the arrow function is a closure that holds this, and this holds the 100,000 points and the canvas element. The canvas is now a : removed from the page, but still referenced from JavaScript. Both files were run in headless Chromium 156, followed by a forced garbage collection through the DevTools protocol and a count of what was left. The wrong version kept all 200 charts alive, about 161 MB of JavaScript heap, and the next resize event logged redraw 200 times for charts nobody could see. The right version left no charts alive and a heap of about 1.2 MB.

The fix uses the signal option of addEventListener. MDN describes it plainly: the listener is removed when abort() is called on the AbortController that owns the signal. One controller per component lets destroy() remove every listener the component added, with one call and without keeping references to each handler.

Data about objects you don't own: WeakMap

Caches keyed by objects are the other classic. A Map from DOM elements to metadata keeps every element alive for as long as the map lives, even after the element leaves the page. A WeakMap doesn't: MDN explains that its keys don't prevent garbage collection, and once a key is collected, its value can be collected too.

JavaScript tooltips.js
const tooltipFor = new WeakMap(); // not new Map()function attachTooltip(element, text) {  tooltipFor.set(element, { text, shownAt: null });}// Once `element` is unreachable everywhere else, its entry// can be collected too. A Map would keep both alive forever.

The price is that you can't list a WeakMap's keys or count them, because that would expose when garbage collection runs. If you need to iterate, you need a Map with explicit deletes or a size limit.

What holds the referenceWhy it lives so longFix
A listener on window or documentThe target lives as long as the pagePass a signal and call abort(), or remove the same function
A setInterval callbackThe timer holds it until it's clearedCall clearInterval in your cleanup
A module-level Map or array cacheModule scope lives as long as the pageCap its size or age, or key it with a WeakMap
A variable pointing at a removed elementThe element can't be collected while referencedDrop the reference when the element is removed

How to apply it in your project

  1. Pair every subscription with its cleanupFor each addEventListener, setInterval, observer or subscription in a component, find the line that undoes it. A component-wide AbortController makes listener cleanup one call.
  2. Give every cache a limitAny Map, array or object that grows at module scope needs a maximum size, an expiry, or object keys in a WeakMap.
  3. Hold DOM elements only as long as they're on the pageWhen a component removes an element, set the fields that point at it to null, or keep them inside the component that gets destroyed along with it.
  4. Test the loop, not the page loadLeaks show up after repetition. Script the action you suspect, run it many times, click the Collect garbage button in DevTools, and compare memory with where you started.

Key takeaways

  • The garbage collector frees what's unreachable; anything your code can still reach stays, needed or not.
  • A JavaScript memory leak is a long-lived object, often window, a timer or a module-level cache, holding a reference you forgot.
  • Every listener, timer and subscription needs a cleanup; AbortController signals make listener cleanup one call.
  • Use WeakMap for data attached to objects you don't control, and cap every other cache.
  • Don't count on WeakRef or finalizers; confirm a fix with repeated actions, a forced GC and a heap snapshot.

📚 المصادر

  1. Memory management — MDN
  2. Fix memory problems — Chrome DevTools
  3. EventTarget: addEventListener() method — MDN
  4. WeakMap — MDN
  5. WeakRef — MDN

التعليقات (0)