Sub topic 3
WeakMap and WeakSet: Where Weakness Started
This chapter assumes you know JavaScript objects and references, how Map and Set work, and that an object is collected once nothing reachable points to it. WeakRef and FinalizationRegistry arrived in ES2021. Before that, WeakMap and WeakSet (ES2015) were the only weak structures in the language. You need to know what they do well, because they are often the better choice.
The Problem They Solve
Suppose you want to attach extra data to objects you don't own, such as DOM nodes or objects from a library. If you use a regular Map, that data stays in memory forever:
const metadata = new Map();
function tag(obj, info) {
metadata.set(obj, info);
}
let node = { id: 1 };
tag(node, { clicks: 0 });
node = null; // the Map still holds the key strongly, so the object is never collectedThe Map keeps a strong reference to every key, so the object stays reachable through the map. A WeakMap fixes this by holding its keys weakly.
const metadata = new WeakMap();
let node = { id: 1 };
metadata.set(node, { clicks: 0 });
console.log(metadata.get(node).clicks); // 0
node = null; // nothing else references the object; key and value can both be collectedHow the Weakness Works
A WeakMap entry behaves like an ephemeron: the value is kept alive only while the key is reachable from somewhere else. The map does not keep the key alive. Once the key is collected, the whole entry disappears.
A WeakSet works the same way without a value. It records whether an object is a member and holds no strong reference to it:
const visited = new WeakSet();
function visit(obj) {
if (visited.has(obj)) return 'already seen';
visited.add(obj);
return 'first visit';
}
const a = {};
console.log(visit(a)); // first visit
console.log(visit(a)); // already seenWhat You Give Up
Garbage collection timing is nondeterministic, so the engine hides the contents of these collections. That keeps your program from observing when collection happens.
| Feature | Map / Set | WeakMap / WeakSet |
|---|---|---|
| Key types | Any value | Objects and non-registered symbols |
| Keeps keys alive | Yes | No |
| Iteration (`keys()`, `forEach`, `for...of`) | Yes | No |
| `size` property | Yes | No |
| `clear()` | Yes | No |
You can only ask about a key you already hold: get, set, has, and delete on a WeakMap, and add, has, and delete on a WeakSet.
Common Errors
- Using primitives as keys.
weakMap.set('id', 1)throws aTypeError. Strings and numbers can't be collected, so they can't be weak keys. - Expecting weak values. Only keys are weak. If the value refers back to its own key (
wm.set(obj, { owner: obj })), the ephemeron rule still lets the entry be collected. But a value referenced from anywhere else stays alive for its own reasons. - Treating a WeakMap as a cache keyed by strings. For a cache like "URL to response", the key is a primitive and the value is what you want held weakly. WeakMap can't do this. A later chapter builds that cache with WeakRef.
Where WeakRef Fits
WeakMap answers "given this object, what is its data?" It never lets you ask "does that object still exist?" WeakRef, covered next, gives you exactly that, and in exchange your code can see when collection happens.
Exercise
You need to track which request objects have already been logged, so that each one is logged only once, without leaking memory after requests finish. Which structure do you use, and why not a Set?
Show answer
Use a WeakSet. It records membership without keeping the request objects alive, so finished requests can be collected. A Set would hold every request strongly and grow without limit.
Exercise
Why does WeakMap have no size property or iteration methods?
Show answer
Collection timing is nondeterministic. If you could count or list the entries, the result would change depending on when the garbage collector ran, and your program could observe GC behavior. Hiding the contents keeps WeakMap's behavior deterministic.