Sub topic 13
Pitfalls and Accidental Strong References
This chapter assumes you know how WeakRef, deref(), FinalizationRegistry, held values, and unregister tokens work, as covered in earlier chapters. The bugs below have one thing in common. Code that looks weak actually holds a strong reference somewhere, so the target never becomes unreachable and is never collected. The engine reports no error when this happens. The memory just stays in use.
Held Values That Point Back to the Target
The registry holds every held value strongly. If the held value is the target itself, register() throws a TypeError. The engine cannot detect indirect references, though. If the held value is an object that refers to the target, it keeps the target alive.
const registry = new FinalizationRegistry((info) => {
console.log(`cleanup for ${info.label}`);
});
let target = { data: new Array(1e6).fill(0) };
// Bad: info.owner is a strong path from the registry to the target
registry.register(target, { label: 'big', owner: target });
// Good: store only the primitive data the callback needs
let other = { data: new Array(1e6).fill(0) };
registry.register(other, { label: 'big-2', size: other.data.length });
target = null;
other = null; // only 'other' can ever be collectedClosures That Capture the Target
The registry also holds its cleanup callback strongly. A callback that closes over a variable bound to the target keeps that target reachable. The same happens with any long-lived closure, such as an event listener or timer, that mentions the object.
let conn = { socket: 'fake-socket' };
// Bad: the callback's closure references conn
const leaky = new FinalizationRegistry(() => {
console.log('closing', conn.socket);
});
leaky.register(conn, 'conn');
// Good: pass what the callback needs as the held value
const safe = new FinalizationRegistry((socket) => {
console.log('closing', socket);
});
let conn2 = { socket: 'fake-socket-2' };
safe.register(conn2, conn2.socket);Holding the deref() Result Too Long
Calling deref() gives you an ordinary strong reference. If you store that result in a class field, a module variable, or an array, the WeakRef no longer does anything.
class Viewer {
constructor(image) {
this.ref = new WeakRef(image);
}
render() {
const img = this.ref.deref(); // local, released when render returns
if (img === undefined) return 'image gone';
return `rendering ${img.name}`;
}
}
const v = new Viewer({ name: 'photo.png' });
console.log(v.render());Call deref() each time you need the target, use the result right away, and let it go out of scope.
Other Common Mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Letting the registry become unreachable | If the registry is collected, its callbacks may never run | Keep the registry in a long-lived variable |
| Deleting cache entries by key alone | A newer value may have been stored under the same key | Check `cache.get(key)?.deref() === undefined` first |
| Using primitives as targets | `new WeakRef(42)` throws a TypeError | Wrap the data in an object |
| Relying on callbacks for correctness | They may run late or not at all | Use explicit cleanup and treat finalization as a backup |
| Passing the target as the held value through a wrapper | The wrapper holds the target strongly | Pass an inner handle or an ID |
Exercise
A developer writes registry.register(el, { el, id: el.id }) so the callback can log the element. Why is el never collected, and how should the call be rewritten?
Show answer
The registry holds the held value strongly, and the held value's el property is a strong reference to the target, so the target stays reachable. Pass only the data the callback needs, for example registry.register(el, el.id).
Exercise
Inside a function, const obj = {}; const r = new FinalizationRegistry(() => console.log(obj)); and then r.register(obj, 'x'). Will the callback ever fire?
Show answer
No. The callback closes over obj, and the registry holds the callback strongly, so obj stays reachable as long as the registry exists. Move the callback out of that scope and pass the information it needs as the held value.