Sub topic 16
Beyond Weak Collections: WeakRef and FinalizationRegistry
This chapter assumes you already know how WeakMap and WeakSet hold their keys weakly, and what reachability means for garbage collection. It also uses classes with private fields, optional chaining (?.), and setTimeout.
WeakMap and WeakSet never tell you when an object has been collected. You cannot list their contents or count them, so your program behaves the same whether the garbage collector has run or not. JavaScript has two lower-level tools that do let you observe collection: WeakRef and FinalizationRegistry. Both arrived in ES2021. This chapter explains what they do, how they differ from weak collections, and why the specification itself recommends avoiding them where possible.
WeakRef: a single weak pointer
A WeakRef wraps one target object and holds it weakly. Its only method is deref(). It returns the target while the target is still alive, and undefined after the garbage collector has reclaimed it.
let config = { theme: 'dark' };
const ref = new WeakRef(config);
console.log(ref.deref()?.theme); // 'dark'
config = null; // the WeakRef is now the only path to the object
// Later, after a collection, ref.deref() may return undefined.The target must be an object or a symbol that was not created with Symbol.for. These are the same rules that apply to WeakMap keys. Passing a primitive such as a string throws a TypeError.
The key difference from WeakMap
A WeakMap entry ties a value to a key. The value stays alive as long as the key is reachable, and you can only read the value if you already hold the key. You never ask the WeakMap whether an object still exists, because you would need that object in hand to ask.
A WeakRef reverses this. You hold the reference without holding the object, and deref() tells you whether the object survived. That is more powerful, and it also makes your program's behavior depend on when the collector happens to run.
Objects stay alive for the current job
Engines guarantee one thing. If you create a WeakRef or call deref() and get an object back, that object will not be collected before the current synchronous job finishes. A job here means the running script or callback, before control returns to the event loop. So two deref() calls in a row inside the same function always agree:
function readTwice(ref) {
const a = ref.deref();
const b = ref.deref();
return a === b; // always true within one synchronous run
}This is why you cannot see a collection happen in the middle of a function. You need to yield to the event loop first.
FinalizationRegistry: a callback after collection
A FinalizationRegistry lets you request a callback that runs some time after a registered object has been collected. You register a target together with a held value. The held value is passed to your callback, because by that point the target no longer exists.
| Method | Purpose |
|---|---|
| `new FinalizationRegistry(callback)` | Creates a registry. `callback` receives the held value. |
| `register(target, heldValue, token?)` | Watches `target`. The optional `token` lets you cancel later. |
| `unregister(token)` | Cancels every registration made with `token`. Returns `true` if any were removed. |
The held value cannot be the target itself. Doing that throws a TypeError, because holding the target strongly would keep it alive forever. The unregister token is held weakly, so using the target as its own token is common and safe.
const leakWarnings = new FinalizationRegistry((fd) => {
console.warn(`Handle ${fd} was garbage collected without close()`);
});
class Handle {
#fd;
constructor(fd) {
this.#fd = fd;
leakWarnings.register(this, fd, this);
}
close() {
console.log(`closing ${this.#fd}`);
leakWarnings.unregister(this);
}
}
const h = new Handle(42);
h.close(); // closing 42This pattern uses the registry as a diagnostic tool. Code should still call close(). The registry only reports cases where someone forgot.
Watching collection happen
Normally you cannot force a collection. Node.js exposes gc() when started with a flag, which is useful for experiments:
// Run with: node --expose-gc weakref-demo.js
let target = { label: 'big object' };
const ref = new WeakRef(target);
const registry = new FinalizationRegistry((held) => {
console.log(`finalized: ${held}`);
});
registry.register(target, 'big object');
console.log(ref.deref()?.label); // 'big object'
target = null;
setTimeout(() => {
globalThis.gc();
console.log(ref.deref()); // usually undefined now
}, 0);The setTimeout matters. Without it, the object would still be kept alive for the current job, so deref() would still return it. Even with it, "usually" is the honest word. The finalized: line typically prints after the undefined, because cleanup callbacks run as separate tasks.
A cache with string keys
The main legitimate use for WeakRef is a cache where a WeakMap does not fit. WeakMap keys must be objects, but caches are often keyed by strings such as URLs or file names. A Map from string to WeakRef lets large values be collected when nothing else uses them. A registry then removes the stale entries.
const cache = new Map();
const cleanup = new FinalizationRegistry((key) => {
const ref = cache.get(key);
// The key may have been reused for a newer object; only delete dead refs.
if (ref && ref.deref() === undefined) {
cache.delete(key);
}
});
function loadImage(name) {
const cached = cache.get(name)?.deref();
if (cached) return cached;
const image = { name, pixels: new Uint8Array(1_000_000) };
cache.set(name, new WeakRef(image));
cleanup.register(image, name);
return image;
}
const a = loadImage('logo.png');
const b = loadImage('logo.png');
console.log(a === b); // true: second call hit the cacheThe check inside the callback matters. Suppose an image was collected, then loadImage stored a fresh one under the same name, and only after that did the old callback run. Deleting the key without checking would throw away the new, live entry.
Choosing between the four weak tools
| Tool | Holds weakly | Observes collection | Typical use |
|---|---|---|---|
| WeakMap | Keys | No | Data attached to objects you already hold |
| WeakSet | Members | No | Marking or tagging objects |
| WeakRef | One target | Yes, through `deref()` | Caches keyed by primitives |
| FinalizationRegistry | Registered targets | Yes, through callbacks | Cleanup hints and leak diagnostics |
Reach for WeakMap or WeakSet first. Their behavior is deterministic, so tests pass the same way every time. Use WeakRef and FinalizationRegistry only when you need a weak reference that you can look up without already holding the object. When you do use them, write code that is correct whether the collector runs immediately, late, or never.
Common mistakes
- Expecting
deref()to returnundefinedright after dropping the last reference, in the same function. The object is kept alive for the current job. - Passing the target as the held value. This throws a
TypeError. - Capturing the target in the callback's closure, for example by referencing a variable that points to it. That keeps the target reachable, so it is never collected.
- Relying on a finalizer for required cleanup. It may never run.
- Writing tests that assert when collection happens. They will be flaky across engines and runs.
Exercise
You call new WeakRef(obj), set obj = null, then immediately call ref.deref() on the next line in the same function. What does it return, and why?
Show answer
It returns the object. Creating a WeakRef keeps its target alive until the current synchronous job ends, so the object cannot be collected before control returns to the event loop.
Exercise
Why does the cache cleanup callback check ref.deref() === undefined before calling cache.delete(key)?
Show answer
The same key may have been filled with a new WeakRef to a live object after the old object was collected but before the callback ran. Without the check, the callback would delete the fresh entry.
Exercise
A teammate wants to use a FinalizationRegistry to flush unsaved user edits to disk when an editor object is collected. What do you recommend?
Show answer
Don't do it. Finalization callbacks may run late or never, including at program exit, so edits could be lost. Save explicitly, for example on a close or save action. A registry can at most log a warning when an editor is collected without having been saved.