WeakMap
A WeakMap is a map whose keys must be objects and are held weakly. If nothing else points at a key, the entry can be collected, and you cannot iterate the map.
Detailed Explanation
Ordinary Map keys keep their values (and the keys themselves) alive. Put a DOM node in a Map and even after you remove the node from the page, the map still holds it. WeakMap is the structure that does not pin the key.
Keys must be objects or non-registered symbols in current engines (historically, objects only). Primitives throw. Values can be anything. Equality is reference equality for objects.
Because keys are weak, the engine is allowed to drop an entry whenever the key is unreachable from anywhere except this WeakMap (and other weak collections). You cannot observe the collection happening. There is no size, no keys(), no values(), no forEach, no clear in the original spec (clear was removed). The API is get, set, has, delete. If you need to list entries, you do not want a WeakMap.
The classic use is per-object metadata you do not own. A library wants to store a cache on a user's object without adding a visible property and without keeping the user alive:
const cache = new WeakMap();
function extra(obj) {
if (!cache.has(obj)) cache.set(obj, compute(obj));
return cache.get(obj);
}
When obj dies, the computed extra dies. The same pattern used to implement "private" instance data before # fields: a WeakMap keyed by this. Prefer # fields when you control the class. Prefer WeakMap when you attach data to objects from outside.
WeakMaps are not serialisable and not cloneable in a useful way. They are a runtime association, not a data structure you send over the network.
What it costs you: opacity and constraints. You cannot dump the map in a debugger the way you dump a Map. You cannot use string keys. You cannot count entries. Tests that expect a key to vanish must drop every other reference and cannot force a GC in portable JS.
Reach for WeakMap when the key's lifetime should own the entry. Reach for Map when you need to iterate, count, or key by primitives. Reach for WeakRef when you need a single weak pointer rather than a dictionary.
Code Examples
const notes = new WeakMap();
let node = { tag: "li" };
notes.set(node, "selected");
console.log(notes.get(node)); // => selected
console.log(notes.has(node)); // => true
notes.delete(node);
console.log(notes.has(node)); // => falseconst priv = new WeakMap();
class Token {
constructor(value) {
priv.set(this, { value });
}
read() {
return priv.get(this).value;
}
}
const t = new Token("abc");
console.log(t.read()); // => abc
console.log(priv.has(t)); // => truetry {
new WeakMap().set("user-1", 1);
} catch (err) {
console.log(err.name); // => TypeError
}Common Gotchas
Primitive keys throw
`weak.set("id", v)` is a `TypeError`. Use `Map` for string keys.
You cannot iterate or ask `size`
if you need a listing, a WeakMap cannot give you one. Keep a parallel array only if you also want those objects kept alive.
Collection is not observable
dropping the last strong reference does not instantly `has === false` in a portable way. Do not write tests that require a GC.