FinalizationRegistry
In one line
FinalizationRegistry lets you register a callback that runs when a registered object is garbage collected.
In simple words
FinalizationRegistry is a low-level API that notifies you when an object is garbage collected. You register an object and a "held value" with the registry; when the object is collected, your finalizer callback runs with the held value. This lets you clean up associated resources.
This is the inverse of WeakMap/WeakSet (which silently drop entries): FinalizationRegistry tells you when the drop happens. It is useful for managing native resources (file handles, WebAssembly memory) tied to JavaScript objects, or for debugging leaks.
Finalizers are not guaranteed to run promptly or at all in some engines, so they are a best-effort notification, not a destructor. Do not rely on them for critical cleanup — pair with explicit close/dispose methods. They are a safety net, not the primary mechanism.
Example
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Object ${heldValue} was garbage collected`);
});
let obj = { data: "something" };
registry.register(obj, "my-object");
obj = null; // make eligible for GC
// ... later, when GC runs: "Object my-object was garbage collected"register ties a held value to the object. When the object is collected, the callback runs with that held value.
Related terms
Related Resources
Related Lessons
- Memory Management
Learn finalization.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.