WeakMap & WeakRef

WeakMap and WeakSet

Example

A WeakMap holds its keys weakly: if nothing else references a key object, the entry can be garbage-collected. Perfect for attaching data to objects without keeping them alive:

const metadata = new WeakMap();
let element = { id: "btn-1" };
metadata.set(element, { clicks: 3 });
console.log(metadata.get(element).clicks, metadata.has(element));
element = null;   // the entry can now be collected automatically
console.log("WeakMap keys must be objects; it is not iterable");

Output

3 true
WeakMap keys must be objects; it is not iterable

WeakRef

new WeakRef(obj) keeps a reference that does not prevent garbage collection; ref.deref() returns the object or undefined once collected. It is meant for caches of large objects. Use it rarely: GC timing is unpredictable.