What is FinalizationRegistry in JavaScript: Explained with Examples
FinalizationRegistry in JavaScript is a built-in object that lets you run cleanup code when an object is garbage collected. It helps you track when objects are removed from memory and perform actions like releasing resources or logging.How It Works
Imagine you have a box with some items, and you want to know when the box is thrown away so you can clean up the items inside. FinalizationRegistry works like a helper that watches the box (an object) and tells you when it is no longer needed and has been cleaned up by JavaScript's memory manager (garbage collector).
When you register an object with FinalizationRegistry, you provide a callback function and a value to identify the object. Once the object is garbage collected, the callback runs with that value, letting you do cleanup tasks. This happens asynchronously and only after the object is fully removed from memory.
This is useful because JavaScript does not normally tell you when an object is deleted, so FinalizationRegistry gives you a way to react to that event safely.
Example
This example shows how to use FinalizationRegistry to log a message when an object is garbage collected.
const registry = new FinalizationRegistry((heldValue) => { console.log(`Object with id ${heldValue} was garbage collected.`); }); function createObject(id) { const obj = { id }; registry.register(obj, id); return obj; } let myObj = createObject(1); myObj = null; // Remove reference to allow garbage collection // Note: Garbage collection timing is unpredictable, so the message may appear later or not immediately.
When to Use
Use FinalizationRegistry when you need to clean up external resources linked to objects that JavaScript manages, such as closing file handles, releasing memory in native code, or unregistering event listeners.
It is helpful in complex applications where objects hold resources outside JavaScript's control and you want to avoid memory leaks by cleaning up after objects are gone.
However, because garbage collection timing is unpredictable, do not rely on FinalizationRegistry for critical program logic or immediate cleanup.
Key Points
- FinalizationRegistry lets you run code after an object is garbage collected.
- It helps manage cleanup of resources tied to objects.
- Callbacks run asynchronously and timing is not guaranteed.
- Do not use it for essential program logic.
- It improves memory management in complex apps.