Sub topic 12
What Weak Collections Can Hold and What They Cannot Do
This chapter assumes you know the Map and Set APIs and the difference between primitive values and object references. It also builds on the previous chapter's idea of reachability: the garbage collector can reclaim any value that the program can no longer reach.
WeakMap and WeakSet hold their keys weakly. A weak reference does not keep its target alive. That one design choice decides which keys these collections accept and which operations they leave out.
What Can Be a Weak Key
A weak key has to be something the garbage collector can actually collect, and something that has a unique identity. Objects meet both conditions. Primitives such as 'id' or 42 do not, because any part of the program can recreate the same value at any time. The string 'id' never becomes unreachable in a way the program could observe.
| Value | WeakMap key / WeakSet value? | Reason |
|---|---|---|
| Objects, arrays, functions, class instances | Yes | Each has a unique identity and can be collected |
| `Symbol('x')` (non-registered) | Yes (ES2023+) | Unique, and can be collected |
| `Symbol.for('x')` (registered) | No | Lives in a global registry, so it is never collected |
| Strings, numbers, booleans, `null`, `undefined`, BigInts | No | Primitives can be recreated, so they have no collectable identity |
Only the key is held weakly. A WeakMap's values can be anything, primitives included, and each value stays alive as long as its key does.
const wm = new WeakMap();
wm.set({}, 'any value is fine');
wm.set(Symbol('tag'), 42); // allowed in ES2023+ engines
for (const bad of ['id', 7, Symbol.for('shared')]) {
try {
wm.set(bad, 1);
} catch (err) {
console.log(String(bad), err instanceof TypeError); // each logs true
}
}
const ws = new WeakSet();
try {
ws.add('id');
} catch (err) {
console.log(err instanceof TypeError); // true
}What Weak Collections Cannot Do
A WeakMap supports only set, get, has, and delete. A WeakSet supports only add, has, and delete. Neither has size, keys(), values(), entries(), forEach, or clear(), and neither is iterable.
const wm = new WeakMap();
try {
wm.set('id', 1);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(wm.size); // undefined
console.log(typeof wm[Symbol.iterator]); // 'undefined'Why These Operations Are Missing
The engine decides when garbage collection runs. If you could read size or loop over the entries, the result would depend on whether a collection had happened yet. The same code could print 3 on one run and 1 on the next. Leaving these operations out keeps the program deterministic: you can only ask about a key you already hold, and while you hold that key, it is reachable, so the answer cannot change under you.
Common Errors
- Using string IDs as keys. Use a regular Map when your keys are primitives.
- Calling
wm.clear(). It does not exist. Replace the collection withnew WeakMap()instead. - Trying to debug by logging a WeakMap's contents. DevTools may show entries, but your code cannot list them.
Exercise
You want to cache data per user, and you have only numeric user IDs. Can you use a WeakMap keyed by the ID, and what happens if you try?
Show answer
No. Numbers are primitives, so weakMap.set(42, data) throws a TypeError. Use a Map keyed by the ID and remove entries yourself, or key a WeakMap by the user object if you have one.
Exercise
Why would a size property on WeakSet make programs nondeterministic?
Show answer
Entries leave the set when the garbage collector reclaims their objects, and the engine picks when that happens. size would change based on GC timing rather than on anything your code did, so the same program could report different values on different runs.