Sub topic 1
How JavaScript Decides What to Collect
Prerequisites
This chapter assumes you know JavaScript objects, references, and closures, the basics of Map and Set, and the event loop at a conceptual level. You should be able to run code in Node.js or a browser console.
Reachability
JavaScript has no free() call. The garbage collector (GC) keeps any value that is reachable, meaning it can be reached by following references from the roots. The roots are globals, the current call stack, and live closures. Any value that cannot be reached this way may be reclaimed. The engine decides when that happens, and the timing differs between engines, between runs, and with memory pressure. So your code cannot predict it.
Strong and Weak References
An ordinary variable or property holds a strong reference, and any strong reference keeps its target alive. A weak reference lets you point at an object without counting toward reachability. If only weak references to an object remain, the GC may collect it.
WeakMap and WeakSet: Where Weakness Started
WeakMap and WeakSet came first. Their keys are held weakly, so attaching metadata to an object does not stop that object from being collected. You cannot iterate them or read their size, though. They answer "what do I know about this object?" but never "which objects do I have?"
| Tool | Holds weakly | Can read target directly |
|---|---|---|
| WeakMap | keys | no, you need the key already |
| WeakSet | members | no |
| WeakRef | its target | yes, via `deref()` |
Creating a WeakRef and Calling deref()
let target = { name: 'large object' };
const ref = new WeakRef(target);
const obj = ref.deref();
if (obj !== undefined) {
console.log(obj.name);
} else {
console.log('Target was garbage collected');
}
target = null; // the WeakRef alone does not keep the object alivederef() returns the target, or undefined once the target has been collected. Call it once, store the result in a local variable, and check that variable. If you call deref() repeatedly, you can get different answers.
What Can Be a Weak Target
A target must be an object or a symbol that is not registered. Primitives such as numbers and strings throw a TypeError. So do symbols from Symbol.for(), because those live forever in the global registry.
new WeakRef(Symbol('local')); // OK
try {
new WeakRef(Symbol.for('app')); // TypeError
} catch (err) {
console.log(err instanceof TypeError); // true
}Exercise
You need to tag DOM nodes with extra data and never list all the tagged nodes. Should you use WeakMap or WeakRef, and why?
Show answer
Use WeakMap. You always start from the node, so a weakly keyed lookup is enough. WeakRef is only needed when you must get the object back later without already holding it.
Exercise
Why does new WeakRef(42) throw?
Show answer
42 is a primitive. It has no identity and is never collected, so it cannot be held weakly. Only objects and non-registered symbols are valid targets.