Sub topic 12
What Weak Collections Can Hold and What They Cannot Do
This chapter assumes you already know the Map and Set APIs and the idea of reachability from the previous chapter. A value is reachable if running code can still get to it, and the garbage collector may reclaim anything that is not reachable. Here you will learn two sets of rules. The first set says which values WeakMap and WeakSet accept as keys. The second says which operations they leave out. Both follow from one design goal: a weak collection must never keep its keys alive.
The Rule for Keys: "Can Be Held Weakly"
The specification has one internal check for every weak collection. It is called CanBeHeldWeakly. A value passes the check if it meets one of these conditions:
- It is an object. This includes plain objects, arrays, functions, class instances, DOM nodes, and boxed primitives such as
Object('id'). - It is a symbol that was not registered with
Symbol.for. Symbols became valid keys in ES2023.
Every other value fails the check. That covers strings, numbers, booleans, bigint, undefined, null, and registered symbols.
Why primitives are rejected
A weak entry should disappear once nothing else can reach its key. Primitives never become unreachable in that sense. Any code can write the string 'id' or the number 42 again at any time and get a value identical to the one you stored. If 'id' were a weak key, the entry would either have to live forever, which makes it a plain Map with extra limits, or vanish at an unpredictable moment while code could still ask for it. Neither outcome is useful, so the language rejects primitives outright.
The same reasoning explains how symbols are treated. Every call to Symbol('x') creates a new symbol that can be lost like an object can. Symbol.for('x') returns the same symbol from a global registry every time, so code can always recreate it. That makes it behave like a string.
const wm = new WeakMap();
wm.set({}, 'object'); // ok
wm.set([], 'array'); // ok
wm.set(function () {}, 'function'); // ok
wm.set(Object('id'), 'boxed string'); // ok: a wrapper object
wm.set(Symbol('local'), 'symbol'); // ok (ES2023+)
wm.set(Symbol.iterator, 'well-known'); // ok: well-known symbols are not registered
const rejected = ['id', 42, 10n, true, undefined, null, Symbol.for('shared')];
for (const key of rejected) {
try {
wm.set(key, 'x');
} catch (err) {
console.log(String(key), err instanceof TypeError); // each prints true
}
}Symbol keys need Node 20 or later, or a current browser. Older engines throw on Symbol('local') as well.
Gotchas with keys
Boxed primitives are legal keys, but two wrappers are two separate objects. wm.set(Object('id'), 1) followed by wm.get(Object('id')) returns undefined. You can only find the entry again through the same wrapper reference, so wrapping a string does not give you string lookups.
Only the write methods validate their input. get, has, and delete accept a primitive without complaint and report that nothing was found:
const wm = new WeakMap();
const ws = new WeakSet();
console.log(wm.get('id')); // undefined, no error
console.log(wm.has(42)); // false
console.log(wm.delete(null)); // false
console.log(ws.has('tag')); // false
try {
ws.add('tag');
} catch (err) {
console.log(err instanceof TypeError); // true
}Because reads stay silent, a bug that passes an ID string where an object belongs will not throw at the lookup. You will see a cache that never hits, or a tag that never seems set. When a weak collection never finds anything, check the key types.
Values Have No Restrictions
The key rule applies only to keys. A WeakMap value can be anything, including primitives and null. The map holds that value strongly, but only for as long as its key stays alive. This key-to-value pairing is called an ephemeron. It brings one consequence you might not expect: a value that refers back to its own key does not keep the key alive.
const meta = new WeakMap();
let node = { name: 'header' };
meta.set(node, { owner: node, createdAt: 0 }); // value points back at key
node = null;
// The only remaining path to the object is through its own value.
// That does not count, so the entry is now eligible for collection.With a regular Map, this entry would stay in memory for as long as the Map exists.
What Weak Collections Cannot Do
Compare the method lists. Each weak collection keeps only the operations that need a key you already hold.
console.log(Object.getOwnPropertyNames(WeakMap.prototype).sort());
// ['constructor', 'delete', 'get', 'has', 'set']
console.log(Object.getOwnPropertyNames(WeakSet.prototype).sort());
// ['add', 'constructor', 'delete', 'has']
const wm = new WeakMap([[{}, 1]]);
console.log(wm.size); // undefined
console.log(typeof wm.keys); // 'undefined'
console.log(typeof wm.forEach); // 'undefined'
console.log(typeof wm[Symbol.iterator]); // 'undefined'| Capability | Map / Set | WeakMap / WeakSet | Reason it is missing |
|---|---|---|---|
| `set`/`add`, `get`, `has`, `delete` | Yes | Yes | You need the key to call them, so they reveal nothing new |
| `size` | Yes | No | The count would change whenever the collector runs |
| `keys`, `values`, `entries`, `for...of` | Yes | No | Listing keys would hand back objects you lost, which brings them back to life |
| `forEach` | Yes | No | Same as iteration |
| `clear()` | Yes | No | Removed before ES2015 was finalized; replace the whole collection instead |
| Primitive keys | Yes | No | Primitives can always be recreated, so they never become unreachable |
| Spread, `Array.from`, `JSON.stringify` | Works | Fails or prints `{}` | All of them depend on iteration |
Why size and iteration would break things
Garbage collection timing depends on the engine. It varies with heap pressure, the engine version, and what else is running. If size existed, the same program could print 3 on one run and 1 on the next, and that difference would come from memory management, not from your code. Iteration is worse. It would return references to objects the rest of the program had dropped, which makes them reachable again and cancels the point of holding them weakly. Without enumeration, a weak collection is deterministic: given the keys you hold, get and has always give the same answers.
This rule also has a security benefit. Code that holds a WeakMap cannot find out which objects other code has stored in it. It can only ask about objects it already has a reference to.
Working without clear()
To empty a weak collection, replace it:
let cache = new WeakMap();
// ...fill it...
cache = new WeakMap(); // old entries become collectable with the old mapThis works as long as no other code still holds a reference to the old map.
Summary of the Rules
- Keys must be objects or unregistered symbols.
setandaddthrow aTypeErrorfor anything else. get,has, anddeletenever throw on bad keys. They returnundefinedorfalse.- Values can be anything, and a value never keeps its own key alive.
- Weak collections have no
size, no iteration, and noclear, because the answers would depend on when the garbage collector runs.
Exercise
Which of these calls throw, and which succeed? ws.add(Symbol('a')), ws.add(Symbol.for('a')), ws.add(Object(5)), ws.has('a'), ws.add(null), where ws is a new WeakSet().
Show answer
ws.add(Symbol('a')) succeeds because the symbol is unregistered. ws.add(Object(5)) succeeds because it is a wrapper object. ws.has('a') returns false and does not throw. ws.add(Symbol.for('a')) throws a TypeError because registered symbols can be recreated. ws.add(null) throws a TypeError because null is not an object.
Exercise
A teammate's cache const cache = new WeakMap() never returns a hit. The lookup is cache.get(user.id), and the store is cache.set(user.id, profile). Nothing appears in the console. What is wrong, and why is there no error at the lookup?
Show answer
user.id is a primitive, probably a number or string, so cache.set should throw a TypeError. If nothing appears, the error is being caught or swallowed somewhere, or the store path never runs. cache.get with a primitive never throws and returns undefined, so the lookup fails silently. Key the cache by the user object itself, or use a Map if the cache must be keyed by ID.
Exercise
Explain why adding a size property to WeakMap would make programs nondeterministic, while has(key) does not.
Show answer
size would count entries whose keys might already be unreachable, so its value would depend on whether the garbage collector had run yet. has(key) needs a key you still hold, which means that key is reachable and its entry cannot have been collected. The answer depends only on what your code did.