Sub topic 11
Reachability and Garbage Collection
This chapter assumes you know the difference between primitive values and object references, and that you have used Map and Set from earlier chapters. Weak collections only make sense once you know how JavaScript decides when an object's memory can be freed, so this chapter covers that first.
The Working Model: Reachability
JavaScript has no free or delete for objects. The engine's garbage collector reclaims memory automatically. It decides what to keep using reachability: an object stays alive if the program can still get to it by following references from a set of starting points called roots.
Roots include:
- Global variables
- Local variables and parameters of functions currently running
- Values captured by closures that are themselves reachable
Anything a reachable object references is also reachable. Anything you cannot get to from a root is garbage, and the collector may free it at some later time.
Dropping the Last Reference
An object becomes collectable when its last reachable reference goes away, not when one particular variable is cleared.
let user = { name: 'Ada' };
let alias = user; // two references to the same object
user = null; // object still reachable through alias
console.log(alias.name); // 'Ada'
alias = null; // no references remain; object is now collectableAfter the last line, nothing in the program can reach { name: 'Ada' }, so the engine is free to reclaim it.
Strong Collections Keep Objects Alive
A Map or Set holds strong references to its keys and values. Storing an object in one counts as a reference, the same as storing it in a variable.
let session = { id: 42 };
const activeSessions = new Map();
activeSessions.set(session, 'logged in');
session = null; // the variable is cleared...
// ...but the Map still references the object, so it is not collectable
for (const [key, value] of activeSessions) {
console.log(key, value); // { id: 42 } 'logged in'
}The object survives because the program can still reach it through activeSessions. That is correct behavior: you can iterate the Map, so the engine has to keep what is inside it. It also causes a common leak. If you attach data to objects through a long-lived Map and never call delete, those objects are never freed, even after every other part of the program has forgotten them.
When Collection Actually Happens
Becoming collectable does not mean being collected right away. The engine runs the collector on its own schedule, based on memory pressure and heuristics. Your code cannot force it, and the language does not promise it will ever run. This matters for what comes next:
| Question | Answer |
|---|---|
| Can you tell when an object is freed? | Not from ordinary code |
| Does setting a variable to `null` free the object? | Only if no other references remain, and even then only eventually |
| Does a `Map` key keep its object alive? | Yes, until the entry is deleted |
Weak collections, covered in the next chapters, hold references that do not count toward reachability. Because their contents can disappear whenever the collector runs, they have to give up some features a normal Map has.
Exercise
In the code below, after the last line runs, is the object { n: 1 } collectable? Explain why or why not. let a = { n: 1 }; const s = new Set([a]); a = null;
Show answer
No. The Set s still holds a strong reference to the object, and s is reachable through a variable, so the object stays reachable. It becomes collectable only after s.delete is called for it, s.clear() is called, or s itself becomes unreachable.
Exercise
Why can't a program reliably log the moment an object is garbage collected using ordinary code?
Show answer
The engine decides when to run the collector based on its own heuristics, and the language makes no guarantee about timing. An unreachable object may be freed much later or not at all, so ordinary code gets no signal at the moment of collection.