WeakRef
A WeakRef is a pointer that does not keep its target alive. ref.deref() returns the object if it has not been collected, or undefined if it has.
Detailed Explanation
WeakMap and WeakSet hide the weak pointer inside a collection. WeakRef exposes one weak pointer as a value you can store, pass, and put in a strong Map (the map keeps the ref, not the target).
const ref = new WeakRef(element);
// later
const el = ref.deref();
if (el) el.textContent = "still here";
The target can disappear between two lines. That is the point and the danger. You must handle undefined. You must not write a cache that assumes deref() works as a normal get.
FinalizationRegistry lets you register a callback that may run after a target is collected. The callback receives a token you chose, not the object (the object is gone). Use it to clean an external resource you already could have cleaned in finally. Do not use it to resurrect objects or to implement dispose that must run.
Hosts delay collection. A WeakRef created in this turn is specified to stay alive until after the current job in many engines (to avoid seeing a collection mid-function). Tests that deref() immediately after dropping a local can still see the object. You cannot write a portable "wait until GC" test without gc() hooks.
What it costs you: nondeterminism. A feature that works on a quiet page can fail under memory pressure when the cache evaporates. Weak caches are an optimisation, not a source of truth. Keep a strong store for data you must have, and use WeakRef for "nice to reuse if it is still around" (decoded images, parsed ASTs).
Reach for WeakRef when you want a cache that must not pin large objects. Reach for WeakMap when the key is an object and the value should die with it. Reach for a strong Map plus eviction when you need predictable hits.
Code Examples
function createWeakCache() {
const refs = new Map();
return {
set(key, obj) {
refs.set(key, new WeakRef(obj));
},
get(key) {
const ref = refs.get(key);
if (!ref) return undefined;
const value = ref.deref();
if (value === undefined) refs.delete(key);
return value;
},
};
}
const cache = createWeakCache();
let payload = { bytes: 1 };
cache.set("a", payload);
console.log(cache.get("a")); // => { bytes: 1 }
payload = null;
// later, cache.get("a") may be undefinedconst registry = new FinalizationRegistry((label) => {
console.log("collected", label);
});
let tmp = { n: 1 };
registry.register(tmp, "tmp");
tmp = null;Common Gotchas
`deref()` can be `undefined` at any later turn
null-check every time. Do not cache the result across awaits without a plan.
`FinalizationRegistry` is not `finally`
it may never run in a short process. Close files and sockets yourself.
A `WeakRef` in a strongly keyed `Map` still needs you to delete empty entries
otherwise the map grows with dead keys.
Same-turn `deref` often still works
do not use that as proof the object will stay.