What is Garbage Collection?

Garbage collection is the engine's automatic memory management: it periodically finds objects that can no longer be reached from your program and frees their memory, so you never free memory manually in JavaScript.

Reachability

An object is kept alive if it can be reached from a root: the global object, the current call stack (local variables and arguments), and active closures, timers or event listeners. Anything not reachable is garbage, even if objects in a group still reference each other (cycles are collected too).

How modern engines do it (V8 as an example)

  • Mark-and-sweep: starting from the roots, mark everything reachable, then reclaim everything unmarked.
  • Generational collection: most objects die young, so new objects go into a small "young generation" collected often and cheaply (a scavenger). Survivors are promoted to the "old generation", which is collected less often.
  • Incremental and concurrent marking: work is split up and done partly on background threads to avoid long pauses that would cause jank.
  • Compaction: moving objects together to reduce fragmentation.

What you control

  • Do not keep references you no longer need (remove listeners, clear timers, empty caches).
  • Use WeakMap, WeakSet and WeakRef when you want to associate data with objects without keeping them alive.
  • FinalizationRegistry lets you run cleanup after an object is collected, but timing is not guaranteed, so never rely on it for program logic.

Observing it

Chrome DevTools' Memory panel (heap snapshots, allocation timelines) shows what is retained and why. performance.memory (Chrome-only) gives rough numbers.

Code example

js
1// Reachability: an object lives as long as something can reach it
2let user = { name: "Ada", avatar: new Array(1_000).fill("pixel") };
3const admins = [user]; // second reference
4user = null; // the object is still reachable through `admins`
5console.log(admins[0].name); // Ada
6admins.length = 0; // now nothing reaches it -> eligible for GC
7
8// Cycles are fine: unreachable groups are collected together
9function makeCycle() {
10 const a = {};
11 const b = { a };
12 a.b = b;
13 return "cycle created";
14}
15console.log(makeCycle()); // a and b reference each other but are unreachable after return
16
17// WeakMap: attach data without keeping the key alive
18const metadata = new WeakMap();
19let element = { id: "button-1" };
20metadata.set(element, { clicks: 3 });
21console.log(metadata.get(element).clicks); // 3
22element = null; // the entry can now be collected automatically
23
24// FinalizationRegistry: optional cleanup after collection (timing not guaranteed)
25const registry = new FinalizationRegistry((label) => console.log(`${label} was collected`));
26registry.register({ big: new Array(10_000) }, "temporary object");
27console.log("registered; the callback may run much later or never in a short script");

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