WeakMap
A Map variant that holds weak references to object keys, allowing them to be garbage-collected when no other references exist.
Syntax
const wm = new WeakMap([[key, value], ...]); Parameters
| Name | Type | Required | Description |
|---|---|---|---|
iterable | Iterable<[object, value]> | null | No | An optional iterable of [key, value] pairs. Keys must be objects or non-registered symbols; primitive keys throw. |
Returns
WeakMap — A new WeakMap instance.
Throws
TypeError— When a primitive (string, number, boolean, null, undefined, or registered symbol) is used as a key.
Examples
// Private metadata without preventing GC
const _private = new WeakMap();
class User {
constructor(name, age) {
_private.set(this, { age });
this.name = name;
}
getAge() { return _private.get(this).age; }
}
const u = new User('Alice', 30);
console.log(u.getAge());
console.log(Object.keys(u)); // age is not enumerable
Output
30
[ 'name' ]
// Memoization cache keyed by object identity
const cache = new WeakMap();
function expensiveCompute(obj) {
if (cache.has(obj)) return cache.get(obj);
const result = JSON.stringify(obj).length; // placeholder
cache.set(obj, result);
return result;
}
const data = { x: 1, y: 2 };
console.log(expensiveCompute(data));
Output
15
Notes
WeakMap keys are held weakly — when the key object is no longer
reachable, its entry is automatically removed by the GC without any
programmer action. As a consequence, WeakMap is not enumerable
and has no `size` property or iteration methods (`keys()`, `values()`,
`entries()`, `forEach()`).
Use cases: private class fields (pre-`#` syntax), DOM node metadata,
and memoisation caches tied to object lifetime.