WeakMap
A Map whose keys must be objects and do not prevent garbage collection.
Available since: ES2015
Syntax
new WeakMap(entries)Parameters
| Parameter | Type | Description |
|---|---|---|
| entries | Iterable | Optional. [object, value] pairs to start with. |
Return value
WeakMapA new collection with weak keys.
Examples
Extra data for an object without changing the object:
const clicks = new WeakMap();
const button = { id: 'save' };
clicks.set(button, 1);
clicks.set(button, clicks.get(button) + 1);
console.log(clicks.get(button));
console.log(clicks.has({ id: 'save' }));Output:
2
falseNotes
When nothing else refers to a key object, its entry disappears by itself — this prevents memory leaks. The price: a WeakMap has no size, cannot be iterated, and strings and numbers cannot be keys.
See also
In the tutorial
- Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.