Sub topic 1
How JavaScript Decides What to Collect
JavaScript programs create objects all the time and never free them by hand. No free() or delete obj returns memory to the system. A component of the engine called the garbage collector (GC) finds memory the program can no longer use and reclaims it. Before you can use WeakRef or FinalizationRegistry correctly, you need a clear picture of how the collector decides what "can no longer use" means and when it acts on that decision.
This chapter covers the reachability model, how a typical collector applies it, and why the timing of collection is nondeterministic. Later chapters build on that.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript objects, references, and closures. You should know that assigning an object to a variable copies a reference, not the object.
- Map and Set basics.
- Promises and the event loop at a conceptual level: tasks, microtasks, and the idea that your code runs in discrete chunks.
- Running JavaScript in a browser console or with Node.js.
You do not need prior knowledge of garbage collection algorithms.
Reachability: the one rule
The JavaScript specification does not describe a particular garbage collection algorithm. It describes liveness: which objects the program could still observe. Engines approximate liveness with reachability.
An object is reachable if the program can get to it by following references from a set of starting points called roots. Anything that is not reachable can be collected.
Roots include:
- The global object (
globalThis) and everything stored on it. - Local variables and parameters of functions currently on the call stack.
- Variables captured by closures that are themselves reachable.
- Pending callbacks held by the host, such as timers, event listeners, and unresolved promise reactions.
- Internal engine references, such as the module map and the job queues.
From the roots, the collector follows every reference: object properties, array elements, Map and Set entries, closure scopes, prototype links, and so on. Every object it reaches stays. Everything else is garbage.
Reachability is not reference counting
Older engines and some other languages use reference counting, which frees an object when the number of references to it drops to zero. Reference counting cannot free cycles: if C points to D and D points to C, both counts stay at one forever.
Modern JavaScript engines (V8, SpiderMonkey, JavaScriptCore) use tracing collectors that start at the roots. Cycles are not a problem. In the diagram above, C and D reference each other, but no path leads to them from a root, so both are collected.
function makeCycle() {
const a = { name: 'a' };
const b = { name: 'b' };
a.partner = b;
b.partner = a;
return 'done';
}
makeCycle();
// After makeCycle returns, a and b are unreachable.
// They reference each other, but a tracing collector frees both.How a tracing collector applies the rule
The classic algorithm is mark-and-sweep:
- Mark. Start from the roots and visit every reachable object, setting a "live" mark on each.
- Sweep. Walk the heap and reclaim every object without a mark.
Real engines add refinements on top of this. The refinements explain why timing is unpredictable.
Generational collection
Most objects die young: temporary arrays, intermediate strings, short-lived closures. Engines split the heap into a young generation and an old generation. The young generation is small and collected often with a fast copying pass, which V8 calls a scavenge. Objects that survive a few young collections are promoted to the old generation, which is collected less often with a full mark-and-sweep or mark-compact pass.
An object you dropped a millisecond ago may be freed almost at once. One that has lived through several cycles may stay in memory, unreachable, until the next major collection, and that could be seconds or minutes away.
Incremental and concurrent marking
Pausing a web page for a full heap scan would cause visible stutter. Engines therefore mark incrementally, interleaving small slices of marking with your code, and concurrently on helper threads. The engine decides when to start, when to pause, and when to finish based on allocation rate, heap size, idle time, and memory pressure from the operating system.
Heuristics, not schedules
A collection usually happens because the engine judged that it was worth doing. Typical triggers:
| Trigger | Effect |
|---|---|
| Young generation fills up | Minor collection soon |
| Old generation grows past a threshold | Major collection scheduled |
| Browser tab is idle | Engine may do GC work in idle time |
| System memory pressure | Engine may collect aggressively |
| Tab in background or low-power mode | GC may be deferred or throttled |
None of these triggers is visible to or controllable by standard JavaScript. That fact is the root of everything this tutorial says about nondeterminism.
Why collection timing is nondeterministic
Three facts combine:
- The specification does not require collection at all. An engine that never freed memory would still conform, though nobody would use it. The specification says an object may be collected once it is no longer live. It never says must.
- Engines differ. V8, SpiderMonkey, and JavaScriptCore use different heap layouts, generation sizes, and heuristics. The same program collects at different moments in Chrome, Firefox, Safari, Node.js, Deno, and Bun.
- The same engine varies from run to run. Heap state, other tabs, available memory, JIT optimizations, and thread scheduling all shift timing.
What keeps objects reachable without your noticing
Optimizations aside, most memory surprises come from references you forgot about. Each item below is a path from a root:
- Closures. A function keeps its enclosing scope alive for as long as the function itself is reachable. Engines often keep only the variables a closure actually uses, but a context shared by sibling closures can retain more than you expect.
- Event listeners and timers.
addEventListenerandsetIntervalhand a callback to the host, which is a root. Everything the callback captures stays alive until you remove the listener or clear the timer. - Caches and registries. A module-level
Mapholding objects keeps every one of them alive forever. - Console logging. DevTools keeps logged objects so you can inspect them, which keeps them reachable while the console is open.
- Pending promises. A promise that never settles keeps its reaction callbacks, and their captured scopes, alive as long as the promise itself is reachable.
The following example runs in Node.js or a browser and shows a closure retaining a large array:
function createCounter() {
const bigBuffer = new Array(1_000_000).fill(0); // roughly 8 MB of numbers
let count = 0;
return {
increment() {
count += 1;
return count;
},
size() {
return bigBuffer.length; // this closure captures bigBuffer
},
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.size()); // 1000000
// While `counter` is reachable, bigBuffer is reachable too,
// because size() closes over it. Removing the last reference
// makes the whole structure eligible for collection:
// counter = null; (would need `let` instead of `const`)If size() were removed, an engine could drop bigBuffer from the retained scope. Whether a given engine actually does so is an implementation detail, so don't rely on it either way.
Why this matters for weak references
Every reference you've seen so far is strong: following it counts toward reachability. WeakRef and FinalizationRegistry, covered in later chapters, add references that let you observe an object without counting toward its reachability. Those references can tell you whether an object still exists, or let you run code after it has been collected. Both answers depend on the collector's timing, which you've now seen is unpredictable.
Keep two consequences in mind for the rest of the tutorial:
- A weakly referenced object can disappear at some unknown time after it becomes unreachable. It might also never disappear.
- Code that reacts to collection must work correctly whether that reaction comes early, late, or never.
Exercise
Objects X and Y reference each other. A local variable in a function that has already returned referenced X. Nothing else references X or Y. Can a modern JavaScript engine collect them, and must it do so before the next event loop turn?
Show answer
Yes, it can collect both. Modern engines use tracing collectors that start from roots, so a cycle with no path from a root is unreachable no matter how its members point to each other. No, the engine is not required to collect them at any particular time. Reachability only makes them eligible, and the specification never requires collection.
Exercise
A page attaches button.addEventListener('click', () => console.log(report.title)), where report is a large object. Later the code sets its own variable report = null. Is the report object now collectable? Explain using roots.
Show answer
No. The host keeps the listener callback as a root while the listener is attached and the button is reachable. The callback's closure captures the report binding. Because report was reassigned to null in that same scope, the closure now sees null too, so the original object is collectable in this case. If the closure had captured a separate const copy of the reference, or the object were reachable another way, it would stay alive until the listener was removed. Tracing the path from each root is the only reliable way to answer.
Exercise
You test some cleanup logic in Chrome and the object is always collected within a second of being dropped. Why is it unsafe to depend on that one-second window?
Show answer
Collection timing depends on engine heuristics, heap state, generation, memory pressure, and idle time, and none of these are specified or stable. Firefox, Safari, Node.js, or the same Chrome build under different load can collect much later or never. The specification only says an unreachable object may be collected, so a one-second window seen in testing is not a guarantee.