Skip to content
jshacks.dev
Fundamentals

How Garbage Collection Works in JavaScript and What It Frees

JavaScript frees objects that can no longer be reached from the roots, so leaks are objects you still reference by accident. See reachability and leaks.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite and TypeScript logos.

You never free memory in JavaScript, and yet processes run out of it. Both facts have the same explanation: the engine frees what you can no longer reach, and "reach" is defined by references your program is still holding. When memory grows without bound, the cause is almost never a bug in the collector. It is an object that something still points at, long after the program stopped needing it. This post explains how reachability decides what lives, how V8's generational collector spends its effort, the five retention patterns that explain most leaks, and the tools that find them. Output is from Node.js 24 as an ES module, and nothing here prints a memory figure that would change between runs. The weak references that let you hold an object without keeping it alive are covered in the post on WeakMap and WeakSet, and the layout of values is in the post on memory management.

Reachability, not counting

An object is alive if you can get to it from a root by following references. Roots are the global object, the variables on the call stack, active timers and listeners, and a few internal handles. Everything else is garbage, even if it still points at other objects.

JavaScript
function makeCycle() {
  const a = { name: "a" };
  const b = { name: "b", partner: a };
  a.partner = b;
  return a;
}

let kept = makeCycle();
console.log(kept.partner.partner === kept);

kept = null;
console.log(kept);

const registry = new FinalizationRegistry(() => {});
let temporary = { payload: new Array(1000).fill(0) };
registry.register(temporary, "temporary");
temporary = null;

console.log(typeof globalThis.gc);
console.log(typeof registry.register);
Text
true
null
undefined
function

The two objects point at each other, and when the last outside reference was dropped, the pair became unreachable and collectable even though each still referenced the other. A collector that only counted references would have kept the cycle forever, and that is why JavaScript engines trace from roots instead. The gc function is undefined because it exists only when Node.js starts with --expose-gc, which is a diagnostic and not a feature to build on. This script cannot observe the collection happening, which is the design: the language gives your code no way to depend on it.

How V8 spends its effort

V8 collects in generations. New objects go into a small young generation that is collected often and cheaply, because most objects die young: temporaries, intermediate arrays, closures for one call. Objects that survive a couple of young collections are promoted to the old generation, which is collected less often by a mark-and-sweep that runs in parts, concurrently with your code where it can, to keep pauses short.

The practical consequences are few. Short-lived garbage is cheap, so creating temporary objects is rarely a problem. Long-lived data costs more, since each old-generation collection must trace it. And a program that keeps allocating large objects that survive long enough to be promoted pays the larger cost. Engines tune these thresholds, so numbers quoted in blog posts age fast. When memory behavior matters, measure it with the tools below.

You can look at what the engine reports without trying to predict it.

JavaScript
import v8 from "node:v8";

const stats = v8.getHeapStatistics();
const usage = process.memoryUsage();

console.log(Object.keys(usage));
console.log(stats.total_heap_size > 0, stats.heap_size_limit > stats.used_heap_size);
console.log(typeof usage.heapUsed, usage.rss > usage.heapUsed);

const before = process.memoryUsage().arrayBuffers;
const big = Buffer.alloc(32 * 1024 * 1024);
const after = process.memoryUsage().arrayBuffers;
console.log(after - before >= big.byteLength);
Text
[ 'rss', 'heapTotal', 'heapUsed', 'external', 'arrayBuffers' ]
true true
number true
true

The statistics show up as numbers, and tests can reasonably assert only relationships between them. heapUsed counts JavaScript objects, external and arrayBuffers count memory outside the managed heap, such as buffers, and rss is the process's total. A large Buffer shows in arrayBuffers and not in heapUsed, which is why a process can grow a lot with a small heap.

The first leak: an unbounded cache

A module-level Map that stores results by key is the commonest leak. It is reachable from a global, so nothing in it is ever freed.

JavaScript
const cache = new Map();
let computed = 0;

function lookup(id) {
  if (!cache.has(id)) {
    computed += 1;
    cache.set(id, { id, data: new Array(100).fill(id) });
  }
  return cache.get(id);
}

for (let id = 0; id < 5000; id++) lookup(id);
console.log(cache.size, computed);

class BoundedCache {
  constructor(limit) {
    this.limit = limit;
    this.entries = new Map();
  }

  get(key, build) {
    if (this.entries.has(key)) {
      const value = this.entries.get(key);
      this.entries.delete(key);
      this.entries.set(key, value);
      return value;
    }
    const value = build(key);
    this.entries.set(key, value);
    if (this.entries.size > this.limit) {
      this.entries.delete(this.entries.keys().next().value);
    }
    return value;
  }
}

const bounded = new BoundedCache(100);
for (let id = 0; id < 5000; id++) bounded.get(id, (key) => ({ key }));
console.log(bounded.entries.size);
Text
5000 5000
100

The plain cache grew to 5,000 entries and would keep growing with the number of distinct keys, since a key space like user ids or URLs has no natural end. The bounded cache evicted the oldest entry whenever it passed its limit, and stopped at 100. The fix is always a policy: a size limit, a time limit or a weak key, and it belongs in the cache's design from the start.

The second leak: listeners and subscriptions

An event emitter holds a strong reference to every listener, and each listener holds its closure. Adding a listener on every request or render without removing it is a leak with a clear signature.

JavaScript
import { EventEmitter } from "node:events";

const bus = new EventEmitter();
bus.setMaxListeners(0);

function handleRequest(id) {
  const buffer = new Array(1000).fill(id);
  bus.on("shutdown", () => buffer.length);
}

for (let id = 0; id < 100; id++) handleRequest(id);
console.log(bus.listenerCount("shutdown"));

function handleRequestSafely(id) {
  const buffer = new Array(1000).fill(id);
  const listener = () => buffer.length;
  bus.on("tick", listener);
  return () => bus.off("tick", listener);
}

const unsubscribers = [];
for (let id = 0; id < 100; id++) unsubscribers.push(handleRequestSafely(id));
console.log(bus.listenerCount("tick"));
unsubscribers.forEach((off) => off());
console.log(bus.listenerCount("tick"));
Text
100
100
0

Each request left a listener behind, and each listener kept its own thousand-element array alive, so memory grew with the request count. The safe version returns an unsubscribe function, and after calling them all, the count dropped to zero. Node.js warns when an emitter has more than ten listeners for one event, a message that names a possible leak, and silencing the warning with setMaxListeners(0) hides the symptom. Treat the warning as information. In browsers the same pattern appears as addEventListener without removeEventListener, and the AbortController signal option removes a group of listeners in one call.

The third leak: timers

A pending timer is a root, and its callback keeps everything it closes over alive. A repeating setInterval is never freed until you clear it.

JavaScript
let retained = 0;

function startPolling(name) {
  const payload = { name, data: new Array(1000).fill(name) };
  const timer = setInterval(() => {
    retained += payload.data.length;
  }, 5);
  return () => clearInterval(timer);
}

const stops = [startPolling("a"), startPolling("b")];
await new Promise((resolve) => setTimeout(resolve, 30));
stops.forEach((stop) => stop());

const afterStop = retained;
await new Promise((resolve) => setTimeout(resolve, 30));
console.log(retained === afterStop, retained > 0);

const background = setInterval(() => {}, 1000);
background.unref();
console.log(typeof background.hasRef, background.hasRef());
Text
true true
function false

After the timers were cleared, no more work ran and the closures became collectable. A long-lived interval that nobody clears keeps its payload and any object it references for the life of the process. unref() marks a timer as not keeping the process alive, which matters for exit but not for memory: the callback and its closure are still retained while the timer is pending. Store the handle, and clear it when the owner is done.

The fourth leak: closures that capture too much

A closure keeps alive the variables it references, and in some engines the whole scope they live in. A small callback created next to a large object can retain the object.

JavaScript
function makeHandler(largeDocument) {
  const summary = largeDocument.text.slice(0, 10);

  return function onClick() {
    return summary;
  };
}

function makeHandlerWasteful(largeDocument) {
  return function onClick() {
    return largeDocument.text.slice(0, 10);
  };
}

const document1 = { text: "x".repeat(1_000_000) };
const lean = makeHandler(document1);
const heavy = makeHandlerWasteful(document1);

console.log(lean().length, heavy().length);
console.log(typeof lean, typeof heavy);
Text
10 10
function function

Both handlers return the same ten characters. The lean one captured only the short summary, so the million-character document could be freed once the caller dropped it. The wasteful one captured the document itself, so as long as the handler lives, the whole string does. Extract what a long-lived callback needs into a small value before creating it.

The fifth leak: references in module state and detached nodes

Anything held by a module-level variable, a singleton, a global registry or a framework store stays until the program ends. In browsers, a DOM node removed from the page but still referenced from a list or a closure stays in memory with its subtree, a leak called a detached node. The remedy is the same in each case: remove the reference when the owner ends, or hold it weakly.

Finding a leak

Leaks show up as steady growth under repeated work, and the method that finds them is comparative. Take a heap snapshot, run the suspect operation many times, force a collection, take another snapshot and compare which object types increased in count. In Node.js, node --inspect with Chrome DevTools takes snapshots, and v8.writeHeapSnapshot() writes one from code. A count of thousands of one class of object, or of closures from one function, points at the owner. A single big allocation is rarely a leak.

JavaScript
import v8 from "node:v8";

console.log(typeof v8.writeHeapSnapshot, typeof v8.getHeapSpaceStatistics);
console.log(v8.getHeapSpaceStatistics().map((space) => space.space_name).slice(0, 3));
Text
function function
[ 'read_only_space', 'new_space', 'old_space' ]

The names of the heap spaces include the young and old generations, and a growing old space under steady load is the symptom to look for. Production tooling adds metrics for heap size over time, so a leak is noticed by a trend and not by a crash.

Where this model stops

Garbage collection frees memory, not other resources: file handles, sockets and database connections need explicit release, with try and finally or the using declaration covered in the post on explicit resource management. The collector also does not return memory to the operating system promptly, so a process's resident size may stay high after a spike. And performance tuning of the collector, with flags like --max-old-space-size, treats a symptom: raising the limit delays the crash of a leaking process and does not cure it.

The model is described informally in the specification's notes on memory, and the formal guarantee is only that reachable objects are not freed. MDN's page on memory management is a good overview, and the Node.js documentation for v8.getHeapStatistics() lists the figures used above.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.