Sub topic 7
FinalizationRegistry and Cleanup Callbacks
This chapter assumes you know JavaScript objects and closures, understand reachability from the earlier chapters, and know the event loop at a conceptual level. Earlier chapters covered WeakRef, which lets you check whether an object still exists. FinalizationRegistry covers the opposite need. It lets your code ask to be notified after an object has been collected, so it can tidy up related state.
The Working Model
A FinalizationRegistry is an object that holds three things:
- A single cleanup callback, which you pass to the constructor.
- A list of registrations. Each registration links a target object to a held value.
- Weak references to each target, so registering an object does not keep it alive.
When the garbage collector reclaims a registered target, the engine may queue a job. That job calls your callback with the held value from that registration. The callback never receives the target, because the target no longer exists.
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Cleaned up: ${heldValue}`);
});
let resource = { id: 42 };
registry.register(resource, 'resource-42');
resource = null; // at some later point the callback may run with 'resource-42'Once resource is set to null, nothing strongly references the object. The registry's link to it is weak, so the object becomes eligible for collection. At some later point the callback may print Cleaned up: resource-42.
The register() Signature
registry.register(target, heldValue, unregisterToken);| Argument | Required | Purpose |
|---|---|---|
| `target` | Yes | The object (or non-registered symbol) to watch. Held weakly. |
| `heldValue` | No | Passed to the callback. Held strongly. Defaults to `undefined`. |
| `unregisterToken` | No | Lets you cancel the registration later. Held weakly. |
You can register the same target more than once, with the same registry or with different registries. Each registration is tracked on its own. Later chapters cover the rules for held values and unregister tokens in detail.
When the Callback Runs
The callback never runs inside the garbage collector, and it never interrupts your code. The engine schedules it as a separate task after collection, much like a timer callback, so it runs on a clean stack between other jobs.
Several consequences follow:
- The callback runs asynchronously, after the code that dropped the reference has finished.
- One cleanup job may process several collected targets, calling the callback once for each.
- An exception thrown in the callback is reported like any other uncaught error. It does not stop later registrations from being processed.
What the Callback Should Do
Keep cleanup callbacks short. They are a good place to remove stale map entries, log a leak warning, or release a small external handle that you identified through the held value. Do not put correctness-critical work in them. As a later chapter explains, the engine does not promise the callback will run at all.
Exercise
A developer writes function setup() { const registry = new FinalizationRegistry(cb); registry.register(bigObject, 'big'); } and calls setup() once. Why might cb never run even after bigObject is collected, and how should they fix it?
Show answer
The registry is a local variable. After setup() returns, nothing references the registry, so the registry itself can be collected, and its pending callbacks may then never fire. Move the registry to module scope or onto a long-lived object so it stays reachable.
Exercise
Why does the cleanup callback receive a held value instead of the target object?
Show answer
The callback runs after the target has been reclaimed, so the target no longer exists. The held value is separate data that the registry keeps strongly, and it tells the callback which registration was finalized.