Sub topic 2
Strong and Weak References
This chapter assumes you know how JavaScript objects and closures work, can use Map and Set, and have read the previous chapter on reachability. The question here is narrower: which references count when the garbage collector decides whether an object is reachable? Most of them count. A few specific language features create references that do not count, and those features are what the rest of this tutorial builds on.
What Makes a Reference Strong
A strong reference is any reference the garbage collector follows when it marks objects as reachable. An object stays alive as long as there is at least one path of strong references from a root (the global object, the current call stack, active closures) to it.
Almost every reference you write in everyday JavaScript is strong:
- A variable or constant binding:
const user = {...} - An object property:
config.logger = logger - An array element:
items.push(item) - A variable captured by a closure
- A key or value stored in a
Map, or a member of aSet - A callback registered with
addEventListener, a timer, or a promise's.then()
The common thread is ownership. A strong reference tells the engine "I may use this object later, so keep it." The engine has no means of knowing whether you actually will, so it keeps the object.
A Map keeps its keys alive
Setting a variable to null removes one strong reference. It does not remove the others, and this is the most common source of unintended retention.
const listeners = new Map();
function attach(element, handler) {
listeners.set(element, handler);
}
let button = { id: 'save' };
attach(button, () => console.log('clicked'));
button = null;
// The object { id: 'save' } is still reachable through the Map's key.
console.log(listeners.size); // 1
for (const [el] of listeners) {
console.log(el.id); // 'save'
}The button binding no longer points at the object, but listeners does. The Map is reachable from the module scope, so its keys and values are reachable too. The object will never be collected unless something calls listeners.delete(...).
A closure keeps its captured variables alive
Closures create strong references that are easy to miss, because nothing in the source code looks like an assignment.
function makeLogger() {
const bigBuffer = new Array(1_000_000).fill(0);
return function log(msg) {
console.log(msg, bigBuffer.length);
};
}
const log = makeLogger();
log('hello'); // hello 1000000
// bigBuffer stays alive for as long as `log` is reachable.log captures bigBuffer, so the array lives as long as the function does. There is a subtler engine detail as well. In V8, the closures created in one scope share a single context object. If one closure in a scope captures a large variable, the other closures from that scope can keep it alive too, even if they never mention it. The specification does not require this, but you will run into it in practice when you look at heap snapshots.
What Makes a Reference Weak
A weak reference is a reference the garbage collector ignores when it decides reachability. If the only paths to an object go through weak references, the object counts as unreachable and may be collected. The weak reference still exists afterwards, but it no longer leads to the object.
JavaScript offers weak references only through dedicated built-ins:
| Feature | What is held weakly | What is held strongly |
|---|---|---|
| `WeakMap` | Keys | Values, but only while their key is alive |
| `WeakSet` | Members | Nothing |
| `WeakRef` | Its target | Nothing |
| `FinalizationRegistry` | Registered targets and unregister tokens | Held values and the cleanup callback |
No syntax makes an ordinary variable or property weak. If you want weakness, you have to choose one of these structures on purpose, and the code that reads through it must handle the case where the object is gone.
The next chapter covers WeakMap and WeakSet, and later chapters cover the WeakRef and FinalizationRegistry APIs in detail. For now, a short preview shows the difference between the two kinds of reference:
let session = { user: 'ada' };
const strongHolder = [session]; // strong: array element
const weakHolder = new WeakRef(session); // weak: WeakRef target
session = null;
// strongHolder[0] still keeps the object alive.
strongHolder.length = 0;
// Now only the WeakRef points at the object.
// The collector is allowed to reclaim it at any point after this job ends.
console.log(weakHolder.deref()); // { user: 'ada' }The last line prints the object every time. Creating a WeakRef guarantees that its target survives until the current synchronous job finishes, and the chapter "Why a deref()'d Target Survives the Current Job" explains why. In a later task, deref() might return undefined, and your code has to be written for both outcomes.
One Strong Path Beats Any Number of Weak Ones
Reachability works per path, and only one path is needed. An object with a hundred weak references and one strong reference is fully alive. An object with only weak references is eligible for collection, however many of them there are.
This has a practical consequence. Wrapping something in a WeakRef does nothing if a strong reference to the same object exists somewhere else. These are the usual places such a reference hides:
- A closure that captures the object, for example a cleanup callback or an event handler
- A
FinalizationRegistryheld value that is, or contains, the target - A debugging aid such as
console.log(obj). DevTools can keep logged objects alive while the console is open. - A second cache or an index you forgot about, such as a
Mapfrom id to object
The chapter "Pitfalls and Accidental Strong References" covers these cases in depth. The rule to keep in mind now is that a weak reference only helps when it is the only kind of reference left.
Why Strong Is the Default
Weak references are less common because they push work onto every reader. With a strong reference, obj.name always works. With a weak reference, each access becomes "is it still there?", and the answer depends on when the collector happened to run. That timing changes between engines, between runs, and with memory pressure.
The trade-offs compare like this:
| Concern | Strong reference | Weak reference |
|---|---|---|
| Object available when read | Always | Maybe |
| Code at each access | None | Must handle absence |
| Determinism | Deterministic | Depends on GC timing |
| Risk | Memory leaks | Lost data, flaky behavior |
| Who controls lifetime | The holder | Someone else |
The last row is the useful decision criterion. Use a strong reference when your code owns the object's lifetime, meaning the object should exist because you are holding it. Use a weak reference when someone else owns the lifetime and you only want to attach information to the object, or reuse it while it happens to exist. Caches, metadata attached to objects you do not control, and observers that should not keep their subjects alive all fit this second case.
Weak Is Not the Same as Optional
A reference that may be null or undefined is different from a weak reference. When you write this.parent = null, you deterministically remove a strong reference at a time you choose. A weak reference keeps its link until the engine decides to collect the target, and you get no say in when that happens. If your code needs to know when a relationship ends, model the end explicitly: call a dispose() method, remove a listener, or delete a map entry. Weak references tell you that an object was collected at some point. They never tell you when.
Exercise
In the Map example above, button = null did not free the object. Name two different changes that would let the object be collected, and say which one keeps the program deterministic.
Show answer
The first is to call listeners.delete(el) (or listeners.clear()) when the button is no longer needed. This removes the strong key reference at a known moment, so the behavior is deterministic. The second is to replace Map with WeakMap. The key is then held weakly, so once no other strong references remain, the object and its handler become collectable at a time the engine chooses. This is not deterministic.
Exercise
An object is referenced by three WeakRefs, one WeakMap key, and a closure stored in a module-level variable that mentions the object. Can it be garbage collected? Why or why not?
Show answer
No. The closure is reachable from module scope and captures the object, which creates a strong path from a root. One strong path is enough to keep the object alive, whatever weak references also exist.
Exercise
You are writing a library that adds a computed layout record to DOM elements owned by the application. Should the library hold the elements strongly or weakly, and what is the deciding factor?
Show answer
Weakly, for example with a WeakMap keyed by element. The application owns the elements' lifetime, and the library only attaches data to them. Holding them strongly would keep removed elements and their layout records in memory for as long as the library is loaded.