Object-associated metadata
Attach metadata, caches, or private state to objects without making the objects stay alive solely because of that association.
JavaScript · Class
WeakMap stores values using objects or non-registered symbols as keys without strongly retaining those keys. It is useful for object-associated data that should disappear as the key becomes unreachable.
A WeakMap stores values under object or non-registered symbol keys while avoiding strong references to those keys. It supports querying, retrieval, insertion, and deletion, but does not expose key enumeration because garbage collection can change which keys remain live.
new WeakMap()
new WeakMap(iterable)const metadata = new WeakMap();
const user = {};
metadata.set(user, { role: "admin" });
console.log(metadata.get(user).role); // "admin"
console.log(metadata.has(user)); // true
// Once user is no longer referenced elsewhere, its entry can be collected.A WeakMap associates metadata with an object without keeping that object alive solely because it is a key.
Attach metadata, caches, or private state to objects without making the objects stay alive solely because of that association.
Keep computed information for object keys while allowing entries to become collectible when those keys are no longer used.
Hide implementation details behind object identity rather than exposing an ordinary property on the object.
WeakMap holds key/value pairs without strongly retaining its object keys. If a key becomes otherwise unreachable, it may be garbage collected, and its associated value can then become collectible too.
Follow-up: Why is WeakMap not iterable? Because garbage collection can remove keys at nondeterministic times, exposing enumeration would make the observable result depend on garbage-collection state.
WeakMap keys must be objects or non-registered symbols, while values may have any JavaScript type. Operations such as get, set, has, and delete work with a particular key, but there is no operation to list all keys.
Follow-up: When would a Map be preferable? Use Map when keys must be enumerable or when primitive keys such as strings and numbers are needed.
A common use is attaching private or implementation-specific data to objects. The data remains associated with the object while it is reachable, without requiring a separate cleanup step when the object is collected.
Follow-up: How can object identity affect this pattern? A newly created object with the same properties is still a different key, so callers must retain and reuse the original reference.
MapWeakSetWeakMap.prototype.get()WeakMap.prototype.set()WeakMap.prototype.has()WeakMap.prototype.delete()