JavaScript Reference ยท Collections
The WeakMap object
Reference for JavaScript WeakMap: weakly held object keys, get(), set(), has() and delete(), why it cannot be iterated, and patterns like private data and caches.
A WeakMap is a collection of key-value pairs whose keys must be objects (or non-registered symbols). It holds its keys weakly: if nothing else refers to a key object, the garbage collector may remove the object, and the entry disappears with it. The value is kept alive only as long as its key is.
That makes WeakMap the right tool for attaching extra data to objects you do not own, such as DOM elements or objects handed to you by a library, without causing a memory leak.
const meta = new WeakMap(); const user = { name: "Kai" }; meta.set(user, { visits: 1 }); console.log(meta.get(user));
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
new WeakMap() new WeakMap(iterable) weakMap.set(key, value) weakMap.get(key) weakMap.has(key) weakMap.delete(key)
| Name | Description |
|---|---|
iterable |
Optional. An iterable of [key, value] pairs, for example an array of two-element arrays. |
key |
An object, or a symbol that was not created with Symbol.for(). |
value |
Any value. |
Return value: set() returns the WeakMap itself, so calls can be chained. get() returns the stored value or undefined. has() and delete() return a boolean; delete() is true when an entry was removed.
Exceptions: set() and the constructor throw a TypeError when a key is not an object or a non-registered symbol. get(), has() and delete() never throw for other keys; they simply report no entry.
Usage notes
- No size, no iteration. A WeakMap has no
size,keys(),values(),entries(),forEach()orclear(). Which entries exist depends on when the garbage collector runs, so exposing them would make programs behave unpredictably. - Identity, not equality. Two objects with the same contents are different keys, as the second
has()call above shows. - Primitive keys are rejected. Strings, numbers and booleans cannot be keys. Use a regular
Mapfor those. - Only the key is weak. A value that refers back to its own key does not keep the entry alive on its own; the pair is collected once the key is unreachable from anywhere else.
- Good uses: private per-object state, memoizing results for object arguments, remembering metadata about DOM nodes.
- Not for counting or listing. If you need to list entries or know how many exist, use a
Mapand remove entries yourself. - You cannot observe collection. There is no reliable way to see when an entry vanishes. For cleanup callbacks, see
FinalizationRegistry, and read its caveats first.
Browser support
WeakMap is supported by every current browser. Symbols as keys are a newer addition, so check a compatibility table if you rely on them.