Sub topic 13
WeakMap Fundamentals
This chapter assumes you already know the Map API and how garbage collection decides what is reachable. It also assumes you know which keys weak collections accept. Here you will learn the WeakMap API and how WeakMap holds its entries. You will also see the mistakes people make when they treat it like a Map.
What a WeakMap Is
A WeakMap is a key-value collection whose keys must be objects or non-registered symbols. It holds each key weakly. If the rest of the program can no longer reach a key, the garbage collector may remove that key, and its entry disappears with it. A Map works differently: it holds its keys strongly, so a key stays in memory for as long as the Map does.
The API
WeakMap has only four methods, and they behave like their Map counterparts:
| Method | Returns | Notes |
|---|---|---|
| `set(key, value)` | the WeakMap | Chainable; throws `TypeError` for invalid keys |
| `get(key)` | value or `undefined` | Looks up by reference |
| `has(key)` | boolean | Looks up by reference |
| `delete(key)` | boolean | `true` if an entry was removed |
const a = { name: 'a' };
const b = { name: 'b' };
const meta = new WeakMap([[a, 'first']]);
meta.set(b, 'second');
console.log(meta.get(a)); // 'first'
console.log(meta.has(b)); // true
console.log(meta.delete(b)); // true
console.log(meta.has(b)); // false
console.log(meta.get({ name: 'a' })); // undefined: a different objectThe constructor accepts an iterable of [key, value] pairs, the same as Map. Every key in that iterable must be valid, or the constructor throws.
How Entries Are Held
The key is held weakly. The value is held strongly, but only while its key is alive. This pairing is sometimes called an ephemeron. It has a useful result: if a value refers back to its own key, that reference does not keep the key alive.
const owners = new WeakMap();
let doc = { title: 'Report' };
owners.set(doc, { source: doc, loadedAt: Date.now() });
console.log(owners.get(doc).source === doc); // true
doc = null;
// The value still points at the old object, but the only path to that
// value goes through the WeakMap entry, so both can be collected.Common Errors
- Using a string ID as the key.
wm.set('user-1', data)throws aTypeError. Use the user object itself as the key, or use a Map. - Expecting a lookup by structure. A new object with the same properties is a different key, so
getreturnsundefined. - Trying to list entries.
for...of, spread, andObject.entriesdon't work. If you need to enumerate entries, you need a Map. - Assuming the value is weak. A large value is kept for as long as its key is reachable. If the key lives for the whole program, so does the value.
- Using
Symbol.for()keys. Registered symbols are global and never become unreachable, so WeakMap rejects them.
Exercise
You store cache.set(node, { parent: node.parent, self: node }) in a WeakMap, then remove node from the DOM and drop every variable that refers to it. Does the self: node reference in the value stop the entry from being collected? Explain.
Show answer
No. WeakMap entries are ephemerons, so the value is reachable only through its key. A reference from the value back to the key does not count as keeping the key alive. Once nothing outside the WeakMap references node, the key and the value can both be collected.
Exercise
What does new WeakMap().set({}, 1).get({}) return, and why?
Show answer
It returns undefined. The two {} literals create two different objects, and WeakMap compares keys by reference. Also, nothing else references the first object, so its entry can be collected right away.