How do WeakRef and FinalizationRegistry extend the weak-reference capabilities beyond WeakMap/WeakSet?
Short answer
WeakRef lets you hold a weak reference to ANY object (not just as a map key) and later try to access it via .deref(), which returns undefined once collected.
Advertisement
AModel answer
WeakRef lets you hold a weak reference to ANY object (not just as a map key) and later try to access it via .deref(), which returns undefined once collected. FinalizationRegistry lets you register a callback to run (at some unpredictable future point) after an object is actually garbage collected — useful for cleanup, though never guaranteed to run promptly or at all.
const registry = new FinalizationRegistry((heldValue) => {
console.log('cleaned up:', heldValue);
});
let obj = { data: 'large' };
registry.register(obj, 'obj-label');
obj = null; // callback MAY run later, after GCReal-world example
Releasing an external resource (like a native handle) tied to a JS object once that object is no longer reachable.
Likely follow-ups
- Why does the spec explicitly discourage relying on FinalizationRegistry for critical program logic?
Related topics