WeakMap

A collection of key/value pairs with object keys held weakly.

Since ES2015 (ES6) Spec ↗

Syntax

const wm = new WeakMap()

Examples

const wm = new WeakMap();
const key = {};
wm.set(key, "data");
console.log(wm.get(key));
console.log(wm.has(key));
Output
data
true
const wm = new WeakMap();
const k = { id: 1 };
wm.set(k, 42);
wm.delete(k);
console.log(wm.has(k));
Output
false

Notes

- Keys must be objects (or non-registered symbols) and are held weakly, so entries can be garbage-collected when the key is unreachable. - Not iterable and has no `size`; only `get`, `set`, `has`, `delete`. - Useful for attaching private metadata to objects without leaks.

Browser & runtime support

EnvironmentSince version
chrome 36
firefox 6
safari 8
edge 12
node 0.12

See also