Skip to content

Weak references

Keys must be objects; held weakly — if key object is collected, entry disappears.

const meta = new WeakMap();
function attachMeta(domNode, data) {
meta.set(domNode, data);
// when domNode is GC'd, meta entry goes too
}

Use when: metadata for DOM/object lifecycle tied to that object.

Don’t use when: you need a string-keyed cache (keys aren’t objects).

const registry = new FinalizationRegistry((held) => {
console.log('cleaned up', held);
});
function track(obj, id) {
const ref = new WeakRef(obj);
registry.register(obj, id);
return ref;
}

Rare in app code — useful for custom pools and native interop.

flowchart TD
  strong[Strong reference] --> alive[Object kept alive]
  weak[WeakMap key] -.-> maybe[Object may be collected]

If you also store the same object in a global Array, WeakMap won’t help.

const cache = new Map();
const weak = new WeakMap();
cache.set(id, hugeObject);
weak.set(hugeObject, meta); // hugeObject kept alive by Map key/value
const weak = new WeakMap();
// only weak reference — no strong Map entry