Sub topic 13
WeakMap Fundamentals
This chapter assumes you already know the Map API (set, get, has, delete). It also assumes you have read the earlier chapters on reachability and on the rules for weak keys. Here you will learn the WeakMap API itself: how its entries behave over their lifetime, and how it differs from a Map in daily use. The next chapter builds caches and private data on top of it.
What a WeakMap Is
A WeakMap is a key-value collection whose keys are held weakly. If the WeakMap is the only thing still referring to a key object, that reference does not keep the object alive. Once nothing else can reach the key, the garbage collector may reclaim the key, and the whole entry goes with it, value included.
That one rule explains the API. A Map lets you list its contents. A WeakMap only answers questions about a key you already have: "what is stored for this object?" or "is anything stored for this object?"
The API Surface
A WeakMap has four methods and a constructor. There is no size, clear, keys, values, entries, or forEach.
| Member | Returns | Notes |
|---|---|---|
| `new WeakMap(iterable?)` | a WeakMap | Optional iterable of `[key, value]` pairs |
| `set(key, value)` | the WeakMap | Chainable, and throws `TypeError` for an invalid key |
| `get(key)` | the value or `undefined` | Returns `undefined` for invalid keys instead of throwing |
| `has(key)` | boolean | Returns `false` for invalid keys |
| `delete(key)` | boolean | `true` if an entry was removed |
const alice = { name: 'Alice' };
const bob = { name: 'Bob' };
const lastSeen = new WeakMap([
[alice, '2026-11-20'],
[bob, '2026-11-22']
]);
lastSeen.set(alice, '2026-11-24').set({ name: 'Carol' }, '2026-11-01');
console.log(lastSeen.get(alice)); // '2026-11-24'
console.log(lastSeen.has(bob)); // true
console.log(lastSeen.delete(bob)); // true
console.log(lastSeen.delete(bob)); // false
console.log(lastSeen.get({ name: 'Bob' })); // undefinedThe last line shows that lookups use object identity, the same way a Map compares object keys. A new object with the same properties is a different key. The Carol entry is also worth a look. Nothing else refers to that object literal, so the program can never look the entry up again, and the garbage collector is free to remove it.
Invalid keys: set throws, the others do not
Only set rejects a bad key loudly. The read and delete methods treat an invalid key as "not present." Code written this way can probe safely without a try block.
const wm = new WeakMap();
console.log(wm.get('id')); // undefined
console.log(wm.has(42)); // false
console.log(wm.delete(null)); // false
try {
wm.set('id', 1);
} catch (err) {
console.log(err.message); // e.g. "Invalid value used as weak map key"
}The exact error text differs between engines. Check for TypeError, not for the message.
Symbol keys
Since ES2023, a WeakMap also accepts symbols that are not registered, such as those made with Symbol('label'). Registered symbols from Symbol.for() are rejected, because the global registry keeps them alive forever. Well-known symbols such as Symbol.iterator live forever too, and engines differ on whether they accept them, so avoid using them as keys.
const wm = new WeakMap();
const token = Symbol('session');
wm.set(token, { started: Date.now() });
console.log(wm.has(token)); // true
try {
wm.set(Symbol.for('session'), {});
} catch (err) {
console.log(err instanceof TypeError); // true
}Engines older than this feature throw on every symbol key. If you need to support older runtimes, stick to object keys.
How Entries Live and Die
The weakness is in the key-to-entry link. The value is held strongly, but only as long as its key is alive. This pairing is called an ephemeron.
Ephemeron semantics have a useful result. A value that refers back to its own key does not keep that key alive. With a Map, this kind of cycle would last as long as the Map does.
const meta = new WeakMap();
let node = { id: 7 };
meta.set(node, { owner: node, createdAt: Date.now() });
console.log(meta.get(node).owner === node); // true
node = null;
// The only remaining references are inside the WeakMap entry.
// The key and the value are now both eligible for collection.You cannot watch the collection happen from ordinary code, because WeakMap gives you no way to count or list its entries. That limit is deliberate. If you could observe it, your program would depend on when the collector happens to run.
Contrast with Map
const strong = new Map();
let session = { user: 'alice' };
strong.set(session, 'data');
session = null;
console.log(strong.size); // 1
console.log([...strong.keys()][0].user); // 'alice' — still aliveThe Map keeps its key alive and lets you get it back by iterating. That works when you want to own the objects. It becomes a leak when you only meant to annotate objects that belong to someone else.
Common Gotchas
Something else still holds the key
A WeakMap only helps if nothing else holds the key strongly. Common culprits are a listener array, a Map used for logging, a closure kept in a long-lived scope, or a value that is also stored somewhere outside the WeakMap.
const extra = new WeakMap();
const allValues = []; // strong, long-lived
function tag(obj) {
const info = { obj, tags: [] };
extra.set(obj, info);
allValues.push(info); // leak: info is reachable from allValues, and info.obj keeps obj alive
}The ephemeron rule protects you only from references that live inside the entry. A strong path from outside, here through allValues, keeps the key alive as usual.
There is no clear()
clear() was removed from the specification before engines shipped it. To drop every entry, replace the WeakMap:
let registry = new WeakMap();
function resetRegistry() {
registry = new WeakMap(); // old entries become collectable along with the old map
}This only works if every piece of code reads registry through the same binding and none of it keeps a private reference to the old map.
You need to list entries after all
If you find yourself wanting size or a loop over the entries, the WeakMap is the wrong choice for that job. Either use a Map and delete entries yourself, or keep a separate collection of the keys you care about. Keep in mind that a strong collection of keys cancels the weakness.
Debugging tools show entries
Browser DevTools and Node's util.inspect can display WeakMap entries. That is a debugging feature and not part of the language. Entries you see there may disappear the next time the collector runs.
Map or WeakMap at a Glance
| Question | Map | WeakMap |
|---|---|---|
| Primitive keys? | Yes | No (objects and unregistered symbols only) |
| Keeps keys alive? | Yes | No |
| `size`, iteration, `clear`? | Yes | No |
| Typical role | Owning a dataset | Attaching data to objects owned elsewhere |
Use a WeakMap when the key's lifetime is controlled by someone else and your data should go away when that key does. In every other case, a Map is simpler and easier to debug.
Exercises
Exercise
What does this print, and why? const wm = new WeakMap(); console.log(wm.has('a'), wm.get(1), wm.delete(true));
Show answer
It prints "false undefined false". Only set throws for an invalid key. has, get, and delete treat a primitive key as absent and return false, undefined, and false.
Exercise
An entry's value is an object whose property points back to the entry's key. No other code refers to the key. Can the garbage collector reclaim the key? Would the answer change with a Map?
Show answer
Yes. Under ephemeron semantics, a value is reachable only through its key, so a reference from the value back to the key does not keep the key alive. With a Map, the Map holds the key strongly, so both the key and the value stay alive until the entry is deleted or the Map itself becomes unreachable.
Exercise
Write a function resetAll that removes every entry from a module-level WeakMap named store.
Show answer
Declare the map with let store = new WeakMap(); and define function resetAll() { store = new WeakMap(); }. WeakMap has no clear method. Replacing the map makes the old entries unreachable, as long as no other code holds a reference to the old map.
Exercise
Why does new WeakMap().set(Symbol.for('x'), 1) throw while new WeakMap().set(Symbol('x'), 1) succeeds in an ES2023 engine?
Show answer
Symbol.for registers the symbol in the global symbol registry, so it can never become unreachable and would never be collected. Weak collections reject keys like that. A symbol created with Symbol('x') is unregistered and can be collected, so it is a valid key.