Sub topic 3
Reachability: What the Garbage Collector Keeps
This chapter assumes you know JavaScript variables, objects, arrays, and functions. You should also understand closures and scope at a basic level, and be able to run code in a browser console or Node.js. Earlier chapters covered the allocate-use-release lifecycle and how primitives and references differ. Here we answer the question that every garbage collector has to settle: which objects must stay in memory, and which can be freed?
JavaScript's answer is reachability. An object stays alive if your program can still get to it by following references from a fixed set of starting points. If no such path exists, the object is garbage, whatever else is true about it.
The working model
A garbage collector does not try to predict whether your code will use an object again. Predicting that in general is impossible, because it would mean deciding what an arbitrary program will do next. The collector asks a simpler question that it can answer: could the program reach this object?
The model has two parts:
- Roots are references the engine treats as alive without needing any further proof.
- Reachable objects are the roots, plus anything referenced by a reachable object, followed transitively.
Everything else is unreachable. The engine may reclaim it at any time, and you cannot get it back, because by definition no code holds a path to it.
In the diagram, settings has no root pointing directly at it, yet it survives because global → config → settings is a path. Objects A and B reference each other, but no root leads to either one, so both can be collected. The chapter on reference counting explains why that cycle once caused trouble. Under reachability it is no problem.
What counts as a root
The exact list depends on the engine, but the categories are the same across V8, SpiderMonkey, and JavaScriptCore.
| Root category | Examples | Lifetime |
|---|---|---|
| Global object | `globalThis`, `window` properties, top-level `var` and function declarations in scripts | Life of the page or process |
| Top-level lexical bindings | Top-level `let`, `const`, `class` in scripts and modules | Life of the realm or module |
| Active call stack | Local variables and parameters of every function currently executing | Until each function returns |
| Captured scopes | Variables a reachable closure uses | As long as the closure is reachable |
| Pending host work | Timer callbacks, registered event listeners, pending promise reactions, open sockets or file handles in Node.js | Until cleared, removed, settled, or closed |
| Engine and host internals | DOM tree of the current document, handles held by native code or extensions | Varies |
Captured scopes are not strictly roots. A closure's scope is reachable only because the closure itself is reachable. The table lists them because in practice they behave like extra roots that you didn't declare. The chapter on closures covers them in detail.
Pending host work is the category people miss most often. A timer you scheduled is held by the event loop, so its callback is reachable even if no variable in your code refers to it:
function startPolling() {
const state = { ticks: 0, buffer: new Array(100_000).fill("x") };
setInterval(() => {
state.ticks++;
}, 1000);
}
startPolling();
// startPolling has returned and its locals are off the stack,
// but the interval callback is held by the event loop.
// The callback captures `state`, so `state` and its 100,000-element
// buffer remain reachable indefinitely.Nothing in your code points to state any more, but the path event loop → interval callback → captured scope → state → buffer still exists.
Reachability is about paths, not counts
Here is the basic case:
let user = { name: "Ada" };
let admin = user;
user = null; // the object is still reachable through admin
admin = null; // now unreachable and eligible for collectionSetting user = null does not touch the object. It removes one path to it. The object becomes collectable only once the last path is gone. Assigning null destroys nothing. It only cuts a link.
Paths can be indirect, and removing a path in the middle cuts off everything below it:
let company = {
ceo: { name: "Grace", assistant: { name: "Linus" } },
};
const assistant = company.ceo.assistant;
company.ceo = null;
// The ceo object is now unreachable.
// The assistant object is still reachable through the `assistant` const,
// even though the object that originally held it is gone.
console.log(assistant.name); // "Linus"Ownership is not part of the model. An object is not "owned" by whoever created it or by the object that first held it. Any path from any root keeps it alive.
Edge cases and common errors
Reachable is not the same as useful
The collector is conservative in one specific sense. It keeps everything reachable, including data your program will never read again. Most leaks in JavaScript are of this kind: objects that are reachable but dead from the program's point of view.
const seen = [];
function handleRequest(req) {
seen.push(req); // added "for debugging", never read
return { status: 200 };
}
for (let i = 0; i < 5; i++) {
handleRequest({ id: i, body: "payload".repeat(1000) });
}
console.log(seen.length); // 5, and it will keep growingEvery request object stays reachable through globalThis or the module scope, then seen, then the array element. The engine cannot know you will never look at seen. Fixing this is your job, and the chapter on common leaks catalogs these patterns.
Removing a reference does not free memory right away
When the last path disappears, the object becomes eligible for collection. It is not freed at that moment. The engine runs collection when it decides to, usually based on allocation pressure. Watching memory usage straight after you null a variable tells you very little. Later chapters show how to force a collection in diagnostic settings so that measurements make sense.
`delete` and `null` do different things
delete obj.prop removes a property and so cuts the path through it. obj.prop = null keeps the property and also cuts the path. Both make the old value unreachable through obj. Neither frees obj itself. Using delete on a local variable does nothing in sloppy mode and is a syntax error in strict mode. Locals go out of scope when their function returns.
Engines may do better than the model
The language guarantees only that reachable objects stay alive. Engines are allowed to collect sooner when they can prove a value is never used. For example, V8 does not keep a variable alive in a closure's scope if no closure references it. Write your code assuming the plain model, and treat any extra collection as a bonus you cannot count on.
Developer tools create their own roots
Detached DOM nodes
In browsers, the document tree is a root. A DOM node removed from the page is no longer reachable through the document. A JavaScript variable or an array can still point to it, though:
const removed = [];
const panel = document.createElement("div");
panel.textContent = "temporary";
document.body.appendChild(panel);
panel.remove(); // no longer in the document
removed.push(panel); // but still reachable from JavaScriptThe node and its whole subtree stay in memory. DevTools heap snapshots list these as "Detached" elements.
Reasoning through a scenario
When you need to know whether something will be collected, trace backwards. Ask "what references this?" and repeat the question for each answer until you either reach a root or run out of references.
function createSession(userId) {
const profile = { userId, history: [] };
const api = {
record(event) {
profile.history.push(event);
},
};
return api;
}
let session = createSession(42);
session.record("login");
session = null;Tracing backwards from profile:
profileis referenced by the scope ofcreateSession's call.- That scope is referenced by the
recordfunction, which captured it. recordis referenced by theapiobject.apiwas referenced bysession, a top-level binding and therefore a root.
After session = null, step 4 fails and no other path exists. The chain api → record → scope → profile → history is unreachable as a whole and can be collected. If you had also done globalThis.lastSession = session before nulling it, the chain would survive.
Why the model is designed this way
Reachability has three properties that explain why every mainstream engine uses it:
- It is safe. If a path exists, the program could follow it, so freeing the object could cause use-after-free bugs. Keeping every reachable object rules those bugs out.
- It is decidable. The engine can compute it by walking the object graph from the roots. The next chapters describe two ways to do that walk: reference counting, which approximates reachability and breaks on cycles, and mark-and-sweep, which computes it directly.
- It is independent of cycles. Whether two objects point at each other does not matter. Only paths from roots count.
The cost of the model is the gap between "reachable" and "will be used." Garbage collection in JavaScript cannot close that gap for you. You close it by cutting paths you no longer need.
Exercise
After the code below runs, which of the objects a, b, and c can be collected, and why?
let a = { name: "a" };
let b = { name: "b", ref: a };
const c = { name: "c", ref: b };
a = null;
b = null;
Show answer
None of them. c is a top-level const, which is a root. c.ref points to the object originally held by b, and that object's ref points to the object originally held by a. Setting a and b to null removed two paths, but the path c → b-object → a-object still exists.
Exercise
A function calls setTimeout(() => console.log(config.url), 60000), where config is a large local object, and then returns. Is config reachable during the next minute? What happens after the callback runs?
Show answer
Yes. The pending timer is host work held by the event loop, the callback is reachable from it, and the callback captures config. After the callback runs once, the timer drops its reference to the callback. If nothing else refers to the callback or config, both become unreachable and eligible for collection.
Exercise
You remove a list item with li.remove(), but a click-tracking module keeps lastClicked = li. Explain using reachability why the element is not freed, and give one fix.
Show answer
The element is no longer reachable through the document root, but lastClicked is a module-level binding, so the path module scope → lastClicked → li keeps the element and its subtree alive as a detached DOM node. Fix it by setting lastClicked = null when the item is removed, or by storing per-element data in a structure that does not keep its keys alive, which a later chapter covers.