Sub topic 13
Symbols as WeakMap Keys
This chapter assumes you already know how WeakMap works with object keys, and how Symbol() differs from Symbol.for(), which earlier chapters covered. It explains which symbols you can use as weak keys and why registered symbols are rejected.
From Objects-Only to Symbols
A WeakMap holds its keys weakly. If nothing else refers to a key, the garbage collector can reclaim the key, and its entry disappears with it. Before ES2023, a weak key had to be an object. Any primitive, symbols included, threw a TypeError.
ES2023 relaxed that rule. Symbols that are not in the global registry can now be weak keys. The same rule covers WeakSet, WeakRef, and FinalizationRegistry, because all four use one internal check: can this value be held weakly?
const token = Symbol('session');
const meta = new WeakMap();
meta.set(token, { createdAt: Date.now() });
console.log(meta.has(token)); // true
console.log(meta.get(token).createdAt > 0); // true
const seen = new WeakSet();
seen.add(Symbol('job')); // allowed
console.log(seen instanceof WeakSet); // trueWhy Registered Symbols Are Rejected
A weak key only makes sense if it can become unreachable. A symbol from Symbol.for('app.theme') can never become unreachable, because any code can call Symbol.for('app.theme') again and get the same symbol back. The registry keeps it alive for the whole lifetime of the realm. An entry keyed by it would never be collected, so the language refuses it instead of quietly leaking memory.
const registered = Symbol.for('app.theme');
const map = new WeakMap();
try {
map.set(registered, 'dark');
} catch (e) {
console.log(e instanceof TypeError); // true
}Well-known symbols such as Symbol.iterator also live forever, but the specification still accepts them, because they are not in the registry. Using one as a weak key is legal and pointless: the entry stays alive as long as the realm does.
Which Keys Work
| Key | Allowed as weak key | Can be collected |
|---|---|---|
| Object | Yes | Yes |
| `Symbol('x')` | Yes (ES2023+) | Yes |
| `Symbol.iterator` and other well-known symbols | Yes | No |
| `Symbol.for('x')` | No, `TypeError` | Not applicable |
| String, number, other primitives | No, `TypeError` | Not applicable |
When This Is Useful
Symbols work well as lightweight, unforgeable handles. Because a unique symbol cannot be recreated, only code that received the token can look up its data. You also don't need to allocate an empty object just to have something to key on. When the last reference to the token is gone, the associated data can be collected.
const store = new WeakMap();
function createHandle(data) {
const handle = Symbol('handle');
store.set(handle, data);
return handle;
}
function read(handle) {
return store.get(handle);
}
const h = createHandle({ user: 'Ada' });
console.log(read(h).user); // "Ada"
console.log(read(Symbol('handle'))); // undefined: a lookalike is not the same keyChecking Support
Recent engines support this, including Node.js 20 and later. Older runtimes do not, so check a compatibility table before relying on it, or test for it at runtime:
function supportsSymbolWeakKeys() {
try {
new WeakMap().set(Symbol(), true);
return true;
} catch {
return false;
}
}
console.log(supportsSymbolWeakKeys());Exercise
A library calls cache.set(Symbol.for('config'), value) on a WeakMap and crashes. Why, and what are two ways to fix it?
Show answer
Symbol.for returns a registered symbol. Registered symbols can never be collected, so WeakMap rejects them with a TypeError. One fix is to use an unregistered Symbol('config') and share that one symbol through the module that needs it. The other is to switch to a regular Map if the entry is meant to live forever anyway.
Exercise
Is new WeakSet().add(Symbol.asyncIterator) legal, and is it useful?
Show answer
It is legal, because well-known symbols are not in the global registry. It is not useful, because well-known symbols are never collected, so the entry stays as long as the realm exists.