Sub topic 2
Strong and Weak References
This chapter assumes you know how JavaScript objects and closures hold references. It also assumes you read the previous chapter on reachability, where the garbage collector keeps any object it can reach from a root such as a global variable, the call stack, or an active closure. Here we split references into two kinds: references that count toward reachability, and references that do not.
What makes a reference strong
A strong reference is an ordinary reference. A variable, an object property, an array slot, a Map entry, or a variable captured by a closure each points at an object and keeps it reachable. While the garbage collector can follow a chain of strong references from a root to an object, that object stays in memory.
Most memory leaks in JavaScript come from strong references you forgot about, not from bugs in the engine:
const listeners = new Map();
function track(element, data) {
// The Map holds strong references to both the key and the value.
listeners.set(element, data);
}
let el = { id: 'button-1' };
track(el, { clicks: 0 });
el = null;
// The object is still reachable through `listeners`, so it is never collected.
console.log(listeners.size); // 1Setting el to null removed one strong reference. The Map still holds another, so the object stays reachable.
What makes a reference weak
A weak reference points at an object without keeping it alive. The garbage collector ignores weak references when it decides what is reachable. If the only remaining paths to an object go through weak references, the object can be collected. After it is collected, every weak reference to it stops working, and code reading through the weak reference gets nothing back.
The trade-off
Neither kind of reference is better in general. Each one gives up something.
| Property | Strong reference | Weak reference |
|---|---|---|
| Keeps target alive | Yes | No |
| Target always available | Yes, while the reference exists | No, it may disappear at any time |
| Code must handle absence | No | Yes |
| Typical use | Normal program data | Caches, metadata, observing objects you don't own |
A weak reference is useful when your code wants to use an object if it still exists but should not be the reason it exists. A cache is one example: the cached value is worth keeping only while someone else still uses it.
Where JavaScript exposes weakness
JavaScript offers weak references in two forms, and later chapters cover each:
WeakMapandWeakSethold their keys weakly. You cannot list their contents, so you never observe a collection happening.WeakRefholds a single target weakly and lets you ask whether it is still there.FinalizationRegistrynotifies you, at some point, after a target has been collected.
WeakRef and FinalizationRegistry make garbage collection observable, and that is new. Collection timing depends on the engine, so code that reads through a weak reference must handle both outcomes every time.
Common errors
- Assuming
obj = nullfrees the object. It removes one reference. Other references may still keep the object alive. - Expecting a weakly held object to disappear quickly. Collection might happen much later, or never in a short-lived program.
- Capturing the target in a closure stored next to the weak reference. The closure creates a strong reference and defeats the purpose.
Exercise
An object is referenced by a local variable that has gone out of scope, by a WeakRef stored in a global, and by a callback function stored in a global array that uses the object in its body. Can the object be collected? Why or why not?
Show answer
No. The callback's closure captures the object, and the global array holds the callback strongly. That gives a strong path from a root to the object. The WeakRef plays no part in reachability, and the variable that went out of scope no longer counts, but one strong path is enough to keep the object alive.
Exercise
You want to attach metadata to DOM nodes owned by a third-party library without stopping those nodes from being collected when the library removes them. Should the reference from your metadata store to each node be strong or weak?
Show answer
Weak. Your store should not be the reason a node stays in memory. A WeakMap keyed by the node fits this case, because the metadata becomes collectable along with the node.