Sub topic 11
WeakRef and FinalizationRegistry, and Why to Avoid Relying on Them
This chapter assumes you already understand reachability, mark-and-sweep, and the WeakMap/WeakSet APIs from earlier chapters. You should also be comfortable with async/await.
A WeakMap hides collection from you completely. When a key object dies, its entry disappears, and your code never sees it happen. WeakRef and FinalizationRegistry go one step further and let you observe garbage collection directly. That ability is useful in narrow cases. It is also easy to misuse, because the collector decides when, and whether, anything happens.
WeakRef: a reference that does not keep its target alive
A WeakRef holds an object without counting as a path from a root. If the only remaining references to an object are weak, the collector may free it. You read the target with deref(). It returns the object if the object is still alive and undefined if it has been collected.
let config = { theme: "dark" };
const ref = new WeakRef(config);
console.log(ref.deref()?.theme); // "dark"
config = null; // only the weak reference remains
// At some later point, ref.deref() may return undefined.Engines guarantee one thing about timing. After deref() returns an object, that object stays alive until the end of the current synchronous job. Two calls in the same synchronous block give the same answer. Once you await or schedule a callback, that guarantee ends.
FinalizationRegistry: a callback after collection
A FinalizationRegistry lets you ask to be notified after a registered object is collected. You register a target together with a held value, which is what the callback receives. The held value must not be the target itself, because the callback would then need the very object that was freed. Passing the same object for both throws a TypeError.
The example below is a cache of large objects that the collector may reclaim under memory pressure. The registry removes stale Map entries after their objects are gone.
const cache = new Map(); // key -> WeakRef
const registry = new FinalizationRegistry((key) => {
const ref = cache.get(key);
// The key may have been refilled with a new object since then.
if (ref && ref.deref() === undefined) {
cache.delete(key);
}
});
function getImage(key) {
const cached = cache.get(key)?.deref();
if (cached) return cached;
const image = { key, pixels: new Uint8Array(1024 * 1024) };
cache.set(key, new WeakRef(image));
registry.register(image, key);
return image;
}
const a = getImage("logo");
console.log(getImage("logo") === a); // true while `a` is aliveThe check inside the callback matters. Without it, a late callback could delete an entry that now points to a fresh, live image.
Why you must not depend on them
| Assumption | Reality |
|---|---|
| The object is collected soon after it becomes unreachable | The collector may wait indefinitely, especially when memory is plentiful |
| The finalization callback always runs | It may never run, for example if the page closes or the process exits |
| Callbacks run in a predictable order | Engines may batch or reorder them |
| Behavior is the same across engines | V8, SpiderMonkey, and JavaScriptCore schedule collection differently |
Good uses are caches of recomputable data and diagnostics that detect missed cleanup. If your program gives wrong results when collection is delayed or skipped, the design is relying on collection, and you should redesign it.
Exercise
A function calls const user = ref.deref();, then await fetchProfile();, then reads user.name. A teammate says user could be undefined after the await. Are they right?
Show answer
No. user holds a strong reference stored in a local variable, so the object stays alive for as long as user is in scope. The risk is calling ref.deref() again after the await. That second call may return undefined, because the same-job guarantee does not cover code after an await.
Exercise
Why does the cache example's finalization callback check ref.deref() === undefined before deleting the entry?
Show answer
The callback runs at an unpredictable time after collection. By then, getImage may have stored a new WeakRef under the same key. Deleting without the check would remove a valid entry for a live object.