Sub topic 1
How JavaScript Decides What to Collect
JavaScript manages memory for you. You create objects, and the engine frees them when they are no longer needed. To use WeakRef and FinalizationRegistry correctly, you first need to know how the engine decides that an object is "no longer needed", and why you cannot predict when that happens.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript objects, references, and closures
MapandSetbasics- Promises and the event loop at a conceptual level
- Running JavaScript in a browser or Node.js
Reachability: The Core Rule
The garbage collector (GC) is the part of the engine that reclaims memory. Modern engines use reachability to decide what to keep. An object is reachable if the program can still get to it by following references from a root.
Roots include:
- Global variables, such as properties of
globalThis - Local variables and parameters of functions currently on the call stack
- Variables captured by closures that are themselves reachable
- Internal engine references, such as pending promise callbacks and active timers
Anything reachable from a root survives. Anything else may be collected.
The orphan pair in the diagram points to each other in a cycle. Reachability-based collectors handle cycles without trouble: the GC asks whether a root can reach an object, not how many references point to it.
Watching Reachability Change
let user = { name: 'Ada', profile: { theme: 'dark' } };
const profile = user.profile; // second path to the profile object
user = null;
// The outer { name: 'Ada' } object is now unreachable.
// The profile object is still reachable through `profile`.
console.log(profile.theme); // 'dark'Setting user to null does not free anything immediately. It only removes a path. The outer object becomes eligible for collection. The engine will reclaim it at some point it chooses, or possibly never if the program exits first.
Closures can keep objects reachable in ways that are easy to miss:
function makeCounter() {
const bigBuffer = new Array(1_000_000).fill(0);
let count = 0;
return () => {
count += 1;
return bigBuffer.length + count;
};
}
const counter = makeCounter();
console.log(counter()); // 1000001
// bigBuffer stays reachable as long as `counter` is reachable.Why Collection Timing Is Nondeterministic
The specification says which objects may be collected. It does not say when the engine must collect them. Engines such as V8, SpiderMonkey, and JavaScriptCore make that decision with heuristics:
| Factor | Effect on timing |
|---|---|
| Heap size and allocation rate | Collections run more often under memory pressure |
| Generational design | Young objects are scanned often, old objects rarely |
| Incremental and concurrent marking | Work is spread across time and threads |
| Idle time | Browsers may collect while the page is idle |
| Engine version and flags | Heuristics change between releases |
The same program can therefore free an object after 2 ms on one run, after 2 seconds on another, and never on a third.
This is the main constraint behind the weak-reference APIs in later chapters. They let you observe collection, but they cannot make it predictable.
Common Errors
- Assuming
obj = nullfrees memory. It removes one reference. Other references, including closures, may still exist. - Worrying about cycles. Unreachable cycles are collected like any other unreachable objects.
- Forgetting hidden roots. Event listeners, timers, and pending promises can keep objects reachable.
Exercise
After this code runs, which objects are eligible for collection? let a = { b: { c: {} } }; const keep = a.b.c; a = null;
Show answer
The outer object and the b object are unreachable, so both are eligible. The innermost c object stays reachable through keep, so it is not eligible. Being eligible does not mean the engine has collected them yet.
Exercise
Why might two runs of the same program free an unreachable object at different times?
Show answer
The specification defines which objects may be collected but not when. Engines schedule collection with heuristics based on heap pressure, allocation rate, generations, idle time, and engine version, so the timing varies between runs and environments.