Sub topic 8
Held Values: Passing Data to the Callback
The previous chapter introduced FinalizationRegistry and its cleanup callback. This chapter covers the second argument to register(), the held value. It is the only information your callback receives. Choosing it badly can keep the target alive forever, so it needs care.
This chapter assumes you know JavaScript objects, references, and closures, and that you have read the earlier chapters on reachability, WeakRef, and the basic FinalizationRegistry API.
Why the Callback Needs a Held Value
When the callback runs, the target is already gone. The engine has collected it, or is about to, so it cannot hand the target to your code. Passing the target back would bring a dead object back to life, and the design of weak references rules that out.
So the callback needs some other way to know which registration fired and what to clean up. The held value supplies that. You choose it at registration time, and the registry passes it to the callback later.
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Target for ${heldValue} is gone`);
});
let session = { user: 'ada', buffer: new ArrayBuffer(1024) };
registry.register(session, 'session:ada');
session = null; // later, the callback may receive 'session:ada'The full signature is register(target, heldValue, unregisterToken). Only target is required. If you leave out heldValue, the callback receives undefined.
The Registry Holds the Value Strongly
The registry treats its two main arguments in opposite ways:
| Argument | How the registry holds it | Consequence |
|---|---|---|
| `target` | Weakly | The registry does not stop the target from being collected |
| `heldValue` | Strongly | The held value stays alive until the callback runs or the registration is removed |
| `unregisterToken` | Weakly | Covered in the next chapter |
The held value has to be held strongly. If it weren't, it could be collected before the callback ran, and the callback would have nothing to work with. This is also the source of most mistakes with held values. The registry keeps the held value alive, and it also keeps alive everything the held value can reach.
The arrow direction is what decides whether you leak. A target that refers to its held value is fine. Once the target is unreachable, the registry's strong link to the held value doesn't help the target survive. A held value that refers to the target, directly or through other objects, creates a strong path from the registry to the target. The target never becomes unreachable, so the callback never runs.
Rule One: The Held Value Cannot Be the Target
The specification rejects the most obvious version of this mistake. If the held value is the same value as the target, register() throws a TypeError:
const registry = new FinalizationRegistry(() => {});
const obj = {};
try {
registry.register(obj, obj);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // wording varies by engine
}The check uses SameValue, so it catches only the identical value. It does not look inside objects, which leads to the next rule.
Rule Two: The Held Value Must Not Reach the Target Indirectly
The engine accepts this code without complaint, and the target is never collected:
const registry = new FinalizationRegistry((held) => {
console.log('cleaning up', held.label);
});
function leakyRegister() {
const target = { data: new Array(100_000).fill(1) };
// The held value contains the target. No error is thrown.
registry.register(target, { label: 'big array', target });
}
leakyRegister();
// The registry strongly holds { label, target },
// which strongly holds target. The callback can never run.The same leak happens when the reference is buried deeper. For example, the held value is an array that contains a wrapper, and the wrapper holds the target. It also happens when the held value is a function whose closure captures the target:
const registry = new FinalizationRegistry((cleanup) => cleanup());
function leakyClosure() {
const target = { id: 7 };
// The arrow function closes over `target`, so the held value reaches it.
registry.register(target, () => console.log('freed', target.id));
}
leakyClosure();The fix is to copy out the data the callback needs before you register, and capture only that copy:
const registry = new FinalizationRegistry((cleanup) => cleanup());
function safeClosure() {
const target = { id: 7 };
const id = target.id; // copy the primitive
registry.register(target, () => console.log('freed', id));
}
safeClosure();What Makes a Good Held Value
Anything that is not the target is allowed, including primitives, objects, functions, and undefined. The question is what the callback needs and what that choice costs in memory.
| Held value kind | Example | Good for | Watch out for |
|---|---|---|---|
| String or number | `'session:ada'`, `42` | Map keys, IDs, log labels | None; primitives cannot reach the target |
| Small plain object | `{ key, createdAt }` | Several pieces of metadata | Do not include the target or its owners |
| Inner resource handle | A file handle or native pointer wrapper | Releasing an external resource | The handle must not point back to the outer object |
| Function | `() => release(id)` | Custom cleanup logic | Closures capturing the target leak it |
| `undefined` (omitted) | `register(obj)` | Counting collections only | The callback cannot tell registrations apart |
A common, safe design splits an object into an outer wrapper and an inner resource. You register the wrapper as the target and the inner resource as the held value. The wrapper points to the resource, which is the safe direction. The resource does not point back.
const registry = new FinalizationRegistry((handle) => {
console.warn(`Releasing handle ${handle.fd} that was never closed`);
handle.release();
});
class Connection {
constructor(fd) {
// Inner handle: knows nothing about the Connection that owns it.
this.handle = {
fd,
release() {
console.log(`fd ${fd} released`);
},
};
registry.register(this, this.handle);
}
}
let conn = new Connection(3);
conn = null; // the handle stays alive in the registry; the Connection does notThe release method uses fd from the constructor's scope, not this of the Connection, so the handle never reaches the wrapper.
Held Values Live Until the Callback Runs
The registry keeps each held value alive until one of three things happens:
- The cleanup callback runs for that registration. After that, the registry drops its reference to the held value.
- The registration is removed with
unregister(), which the next chapter covers. - The registry itself becomes unreachable and is collected, and its pending registrations go with it.
This has two practical results. First, a large held value costs memory for as long as its target lives, and longer if the callback is slow to run. Keep held values small. An ID that you look up elsewhere is usually better than a copy of the data.
Second, if the registry is collected, the callbacks for its pending registrations will not run. If you depend on the registry, store it somewhere long-lived, such as a module-level constant.
One Target, Many Registrations
You can register the same target more than once, in the same registry or in different ones. Each registration is separate and has its own held value. When the target is collected, the engine may call the callback once per registration:
// Run with: node --expose-gc multi.js
const registry = new FinalizationRegistry((held) => {
console.log('finalized:', held);
});
(function () {
const target = {};
registry.register(target, 'first');
registry.register(target, 'second');
})();
setTimeout(() => {
globalThis.gc();
// Typically logs "finalized: first" and "finalized: second" soon after,
// but neither the order nor the timing is guaranteed.
}, 0);The reverse also works. Many targets can share one held value, such as a single string label. The callback then cannot tell which target was collected, which is fine if you only need to count them.
Valid Combinations at a Glance
| Call | Result |
|---|---|
| `register(obj, 'id')` | Valid |
| `register(obj)` | Valid; callback receives `undefined` |
| `register(obj, obj)` | `TypeError` |
| `register(obj, { obj })` | Valid but leaks: `obj` is never collected |
| `register(obj, otherObj)` | Valid if `otherObj` cannot reach `obj` |
| `register('text', 'id')` | `TypeError`: strings cannot be targets |
| `register(Symbol('s'), 'id')` | Valid: non-registered symbols can be targets |
| `register(Symbol.for('s'), 'id')` | `TypeError`: registered symbols cannot be targets |
The rules for which values can be targets come from the earlier chapter on valid targets. Held values have no such limit: any value works except the target itself.
Exercise
A developer writes registry.register(user, { name: user.name, profile: user.profile }), where user.profile is an object with a owner property set back to user. Will user ever be collected? Explain, and suggest a fix.
Show answer
No. The registry strongly holds the held value, which holds user.profile, and profile.owner points back to user. That gives a strong path from the registry to the target, so user stays reachable and the callback never runs. No error is thrown because the held value is not identical to the target. Fix it by putting only data that cannot reach user into the held value, for example registry.register(user, user.name) or { name: user.name, profileId: user.profile.id }.
Exercise
Why does the registry hold the held value strongly but the target weakly? What would go wrong if both were held strongly, or both weakly?
Show answer
The target must be held weakly so that registering doesn't prevent its collection. The held value must be held strongly so it still exists when the callback runs. If both were strong, the target could never be collected. If both were weak, the held value could be collected first, and the callback would have no data to act on.
Exercise
You register one object twice in the same registry with held values 'a' and 'b', then drop all references to it. What may the callback receive, and what can you not rely on?
Show answer
The callback may be called twice, once with 'a' and once with 'b'. Each registration is independent. You cannot rely on the order of the two calls, on when they happen, or on either call happening at all.