Sub topic 11
Reachability and Garbage Collection
This chapter explains how a JavaScript engine decides which objects it can delete from memory. That decision is the reason WeakMap and WeakSet exist, so it is the groundwork for the weak collection chapters that follow. It assumes you know the difference between primitive values and object references, and that you have worked with Map and Set as covered earlier.
Memory You Never Free by Hand
JavaScript has no free() or delete object call. You create objects, and the engine reclaims them once they can no longer matter to your program. The part of the engine that does this is the garbage collector (GC).
The GC cannot know your intentions. It cannot tell that you have "finished" with an object. It answers a narrower question: can the running program still reach this object in any way? If the answer is no, the object is garbage, because no code path could ever read or change it again.
What "Reachable" Means
Modern engines such as V8, SpiderMonkey, and JavaScriptCore use tracing collection built on reachability:
- The engine starts from a set of roots. Roots include the global object, the local variables and arguments of every function currently on the call stack, closures held by pending callbacks, timers and promise handlers, and objects the host holds (DOM nodes attached to a document, for example).
- It follows every reference out of the roots: object properties, array elements, closure-captured variables, and the entries inside Maps and Sets.
- Everything it reaches is marked live. Everything it never reaches is unreachable, and its memory can be reclaimed.
This is the core of the mark-and-sweep algorithm. Real engines add generations, incremental marking, and concurrent sweeping, but those are speed improvements. The rule itself stays the same.
Two details in this diagram matter.
- Cycles are not a problem. Objects A and B point at each other, but nothing from the roots leads to them. A tracing collector never visits them, so both are reclaimed. Older reference-counting schemes leaked such cycles. Tracing collectors do not.
- Reachability is transitive.
profilehas no root of its own. It stays alive only becauseuseris reachable and refers to it.
Strong References
Every reference you have used so far is a strong reference. A strong reference both lets you reach an object and keeps it alive. Variables, properties, array slots, closure captures, and Map and Set entries are all strong.
let user = { name: 'Ada' };
const admins = [user];
user = null; // the variable no longer refers to the object
console.log(admins[0].name); // 'Ada' — still reachable through the arraySetting user to null removed one path to the object. The array still holds another path, so the object is live. An object becomes collectable only once every strong path to it is gone.
Map and Set Hold Strong References
A Map holds strong references to its keys and to its values. A Set holds strong references to its members. That is required for them to work: map.keys() and set.values() have to be able to hand you every entry back at any time, so the engine cannot throw entries away.
const sessions = new Map();
function login(name) {
const user = { name, loggedInAt: Date.now() };
sessions.set(user, { token: Math.random().toString(36).slice(2) });
return user;
}
let current = login('Grace');
current = null; // the caller has dropped the user
// The Map still reaches the user object through its keys
for (const [user, session] of sessions) {
console.log(user.name, typeof session.token); // Grace string
}
console.log(sessions.size); // 1After current = null, the rest of the program has no interest in that user. The Map is reachable, though (it is a module-level constant), and its key reference is strong. So the user object and its session object both stay in memory for as long as sessions lives.
How Collections Cause Leaks
A memory leak in a garbage-collected language is memory that stays reachable after the program has stopped needing it. Long-lived Maps and Sets are a common cause, because they collect entries quietly.
const metadata = new Map();
function track(element) {
metadata.set(element, { clicks: 0, addedAt: Date.now() });
}
// Simulate a long-running app that creates and discards objects
for (let i = 0; i < 100000; i++) {
const temp = { id: i };
track(temp);
// temp goes out of scope at the end of each iteration...
}
// ...but every one of them is still reachable through the Map
console.log(metadata.size); // 100000Each temp object becomes unreachable from the loop body once its iteration ends. The Map still refers to all 100,000 objects, so none of them can be collected. In a browser, the same pattern with DOM nodes as keys keeps removed elements alive along with their children and event listeners. These are called detached DOM trees, and heap snapshots show them clearly.
There are two ways to fix this.
| Approach | How it works | Downside |
|---|---|---|
| Manual cleanup | Call `map.delete(key)` when the object is retired | You must find every exit path, and one missed path leaks |
| Weak keys | Use a collection whose key references do not keep objects alive | You give up iteration, `size`, and primitive keys |
The second approach is what WeakMap and WeakSet provide.
Weak References
A weak reference lets you reach an object without counting toward keeping it alive. When the GC traces from the roots, it ignores weak references. If the only remaining references to an object are weak, the object is unreachable and can be collected. Any weak entries that pointed at it then disappear.
One state in this diagram matters for everything that follows. An object that is only weakly reachable has not been collected yet. It sits in memory until the GC decides to run, and the language makes no promise about when that will be. It might take milliseconds or minutes, or it might never happen if memory pressure stays low.
Why This Shapes the Weak Collection API
Because collection timing is unpredictable, anything that would reveal it would make program behavior depend on GC timing. Consider what a size property on a weakly keyed map would return. It might report 5 before a GC cycle and 3 after one, with no change in your code. Iteration would have the same problem. Two runs of the same program could produce different output depending on heap pressure, engine version, or device.
The language designers chose determinism, so weak collections leave out exactly the operations that would expose GC timing. The rules about which keys are allowed (only values that can actually be collected) follow from the same reasoning. Both topics are covered in the next chapter.
Common Misconceptions
- "Setting a variable to
nullfrees the object." It removes one reference. The object is freed only when no strong paths remain, and even then only when the GC runs. - "The
deleteoperator frees memory."delete obj.propremoves a property, which removes one reference. It has nothing to do with deallocation directly. - "Circular references leak." Not with tracing collectors. Only cycles that are still reachable from a root are retained.
- "A closure only keeps what it uses." Engines often optimize this, but a closure can keep alive variables from its scope that it never reads. Treat long-lived callbacks as possible retainers.
Exercise
In the code below, after the last line runs, which of the objects a, b, and c can be garbage collected, and why?
const registry = new Set();
let a = { name: 'a' };
let b = { name: 'b', friend: a };
let c = { name: 'c' };
registry.add(b);
a = null;
b = null;
c = null;
Show answer
Only the c object can be collected. The b object is still a member of registry, and Set members are strong references, so b stays reachable from the module scope. The a object has no variable pointing at it, but b.friend refers to it, so it is reachable transitively through registry → b → a. The c object has no remaining references, so it is unreachable.
Exercise
A teammate says a weak map should at least offer a size property "for debugging." Explain why the language does not provide one.
Show answer
The number of live entries in a weak collection changes whenever the garbage collector reclaims a key, and the specification does not define when that happens. A size property would let program output depend on GC timing, which varies between engines, runs, and memory conditions. Leaving it out keeps program behavior deterministic.
Exercise
You store per-request objects as keys in a module-level Map and never call delete. Memory grows steadily in production. Describe the cause in terms of reachability and name two fixes.
Show answer
The module-level Map is reachable from a root for the whole life of the process, and it holds strong references to every key and value. Finished request objects therefore stay reachable and can never be collected. One fix is to call map.delete(request) on every completion and error path. The other is to switch to a WeakMap, so the entry no longer keeps the request object alive once the rest of the program drops it.