Sub topic 13
Symbols as WeakMap Keys
This chapter assumes you know how WeakMap and WeakSet work. That means you know that keys must be values the garbage collector can reclaim, and that weak collections are not iterable. It also assumes you know the difference between Symbol() and Symbol.for() from the chapter on the global registry.
For most of JavaScript's history, only objects could be keys in a WeakMap. ES2023 relaxed that rule. Symbols that are not in the global registry may now be used as weak keys. This chapter covers what changed, why registered symbols are still excluded, and when a symbol works better as a weak key than an object.
What Changed in ES2023
The specification uses an internal check called CanBeHeldWeakly to decide whether a value can be referenced weakly. Before ES2023 it accepted only objects. Now it also accepts symbols for which Symbol.keyFor returns undefined.
The same check is used by every weak-reference API in the language:
| API | Where the check applies |
|---|---|
| `WeakMap` | Keys passed to `set` |
| `WeakSet` | Values passed to `add` |
| `WeakRef` | The target passed to the constructor |
| `FinalizationRegistry` | The target and the unregister token passed to `register` |
Lookups such as get, has, and delete never throw. If you pass a value that could not be a weak key, they return undefined or false.
const meta = new WeakMap();
const local = Symbol('local');
meta.set(local, { createdBy: 'chapter-13' });
console.log(meta.get(local)); // { createdBy: 'chapter-13' }
console.log(meta.has(local)); // true
const seen = new WeakSet();
seen.add(local);
console.log(seen.has(local)); // true
const ref = new WeakRef(local);
console.log(ref.deref() === local); // trueWhy Registered Symbols Are Rejected
A weak reference lets the engine discard an entry once nothing else can reach the key. That only works if the key, once unreachable, can never be produced again.
A symbol from Symbol() meets that condition. When the last reference to it is gone, no code can create an equal value, so the WeakMap entry becomes dead weight the collector can safely remove.
A registered symbol does not meet it. Any code can call Symbol.for('app.theme') at any time and get back the identical symbol. Suppose the engine removed the entry because the symbol looked unreachable. A later Symbol.for('app.theme') would return a key that should still map to the value, and the value would be gone. To stay correct, the engine would have to keep the entry forever. The result would be a weak key that behaves like a strong one, and a memory leak that looks safe. The specification avoids the problem by throwing instead.
const wm = new WeakMap();
try {
wm.set(Symbol.for('shared'), 'value');
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
new WeakSet().add(Symbol.for('shared'));
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
new WeakRef(Symbol.for('shared'));
} catch (e) {
console.log(e instanceof TypeError); // true
}
// Lookups do not throw; they just report "not found".
console.log(wm.has(Symbol.for('shared'))); // false
console.log(wm.get(Symbol.for('shared'))); // undefinedThe Well-Known Symbol Edge Case
Well-known symbols such as Symbol.iterator are not in the global registry. Symbol.keyFor(Symbol.iterator) returns undefined. So they pass the check and can be weak keys:
const wm = new WeakMap();
wm.set(Symbol.iterator, 'allowed');
console.log(wm.get(Symbol.iterator)); // "allowed"They will never be collected, though. Every realm keeps them alive for its whole lifetime. An entry keyed by Symbol.iterator is effectively permanent. The committee debated rejecting them and decided to allow them, because the rule "registered symbols are rejected" is simpler to state and to check than a list of exceptions. Treat this as legal but pointless.
Why Use a Symbol Instead of an Object?
Before ES2023, the usual way to get a unique, collectible key was {} or Object.freeze({}). Symbols have properties that make them a better fit for some designs:
| Property | Plain object key | Non-registered symbol key |
|---|---|---|
| Unique identity | Yes | Yes |
| Can be garbage collected | Yes | Yes |
| Holder can add properties to it | Yes, unless frozen | No, it is a primitive |
| Usable as a property key too | No (converted to `"[object Object]"`) | Yes |
| Debug label | None by default | `description` |
| `typeof` | `"object"` | `"symbol"` |
The main motivation in the proposal was opaque handles. A library gives callers a token that identifies something internal. The token should carry no data, have no mutable surface, and allow the internal state to be freed once the caller drops it. A symbol meets all three needs.
Pattern: Opaque Session Handles
const sessions = new WeakMap();
function openSession(user) {
const handle = Symbol(`session:${user}`);
sessions.set(handle, { user, openedAt: Date.now(), requests: 0 });
return handle;
}
function recordRequest(handle) {
const state = sessions.get(handle);
if (!state) throw new Error('Unknown or closed session');
state.requests += 1;
return state.requests;
}
function closeSession(handle) {
return sessions.delete(handle);
}
let h = openSession('ada');
console.log(h.description); // "session:ada"
console.log(recordRequest(h)); // 1
console.log(recordRequest(h)); // 2
// A forged handle with the same description is a different symbol.
try {
recordRequest(Symbol('session:ada'));
} catch (e) {
console.log(e.message); // "Unknown or closed session"
}
h = null; // Once no references remain, the entry is collectible.The caller cannot read the session state from the handle, cannot attach properties to it, and cannot forge it. The description helps with logging and does nothing for security. If a caller forgets to call closeSession, the state is still reclaimed once the handle becomes unreachable.
Pattern: Cleanup with FinalizationRegistry
Symbols can also be targets for FinalizationRegistry, so you can run cleanup after a handle is collected. A typical case is releasing an external resource.
const registry = new FinalizationRegistry((resourceId) => {
console.log(`release resource ${resourceId}`);
});
function acquire(resourceId) {
const token = Symbol(`resource:${resourceId}`);
registry.register(token, resourceId);
return token;
}
let token = acquire(7);
token = null;
// At some later, unpredictable time the engine may log "release resource 7".Feature Detection
Symbols as weak keys are supported in current Chromium-based browsers, Safari 16.4 and later, and Node.js 20 and later. Check a compatibility table for Firefox and any older runtime you target. The reliable test is to try it:
function symbolsAsWeakKeysSupported() {
try {
new WeakMap().set(Symbol('probe'), true);
return true;
} catch {
return false;
}
}
console.log(symbolsAsWeakKeysSupported());If support is missing, a frozen empty object is the usual fallback handle. It can also be a weak key, though it gives up the description and the ability to work as a property key.
const makeHandle = symbolsAsWeakKeysSupported()
? (label) => Symbol(label)
: () => Object.freeze({});Polyfills cannot add real weak semantics for symbols. A Map fallback would keep every key alive.
Common Errors
- Passing a
Symbol.forkey. This throws aTypeErroratset,add,new WeakRef, orregister. If you need a weak key, the symbol must come fromSymbol(). - Assuming the check is about
description.Symbol('x')andSymbol.for('x')have the same description. Only registration matters. - Expecting entries to vanish. If the symbol is also stored as a property key on a living object, or in an array or a
Map, it remains reachable. - Using a weak map as a cache keyed by recreatable data. A weak key works only when the key's identity is the point. If callers rebuild the key from strings, they want a
Mapor a registry, not weakness. - Relying on
hasto validate input type.wm.has(Symbol.for('x'))returnsfalsewithout throwing. It does not tell you thatsetwould have failed.
Exercise
Which of these calls throw a TypeError, and why? (1) new WeakMap().set(Symbol('a'), 1) (2) new WeakSet().add(Symbol.for('a')) (3) new WeakMap().set(Symbol.asyncIterator, 1) (4) new WeakMap().get(Symbol.for('a'))
Show answer
Only (2) throws. Symbol.for('a') is registered, so it can be recreated and can never be safely collected, and WeakSet.add rejects it. (1) uses a fresh unregistered symbol, which is allowed. (3) is allowed because well-known symbols are not in the registry (Symbol.keyFor returns undefined), even though the entry will never be collected. (4) is a lookup, and lookups never throw; it returns undefined.
Exercise
A teammate writes const KEY = Symbol('cache'); const cache = new WeakMap(); cache.set(KEY, bigData); at the top level of a module and expects bigData to be freed when it is no longer needed. Will it be? What would you change?
Show answer
No. KEY is a module-level constant, so it stays reachable for the module's lifetime, and the WeakMap entry and bigData stay with it. Weakness helps only when the key's lifetime matches the data's lifetime. Either key the WeakMap by the object or handle whose lifetime should control the data, or keep the data in a normal variable and set it to null (or delete the entry) when it is no longer needed.
Exercise
Why might a library prefer to return Symbol('conn:42') rather than Object.freeze({}) as an opaque connection handle, assuming the runtime supports symbols as weak keys?
Show answer
Both are unique and collectible. The symbol is a primitive, so callers cannot attach properties to it, even without freezing. It carries a description for debugging ("conn:42"). It can also be used as a property key if the library or caller wants to tag objects with it. A frozen object has no label, and used as a property key it converts to the string "[object Object]".