JavaScript removes objects from memory by itself once nothing uses them. This is called garbage collection. A FinalizationRegistry lets you ask for a message when that happens: "tell me after this object has been deleted from memory."
You create a registry with a cleanup function, then call register() for every object you want to watch. After a watched object is collected, JavaScript may call your function with a held value, a small piece of data you chose earlier, such as an ID or a name. You can cancel a registration with unregister().
You cannot choose when garbage collection runs, so the cleanup function may be called late, or never. Use a registry for optional extras, and never for work that must happen.
Syntax
JavaScript Syntax
Create a registry, watch an object, and cancel the watch again:
JavaScript
const registry = new FinalizationRegistry((heldValue) => {
console.log("Cleaned up: " + heldValue); // runs later, maybe never
});
const item = { name: "big image" };
registry.register(item, "big image", item); // watch item (item is also the token)
const removed = registry.unregister(item); // stop watching
console.log(removed); // true
Reference
Core Ideas
Ideas every FinalizationRegistry tutorial in this series builds on:
Idea
Example
Remember
Registry
new FinalizationRegistry(callback)
Holds the cleanup function and the list of watched objects
Target
registry.register(obj, "id")
The object to watch; the registry does not keep it alive
Held value
registry.register(obj, "id")
Given to the callback later; it must not be the target
Unregister token
registry.register(obj, "id", token)
Optional object that lets you cancel the registration
unregister()
registry.unregister(token)
Stops watching; returns true or false
Callback
(heldValue) => { ... }
Called after garbage collection, never while your code runs
Garbage collection
automatic
The engine frees unused objects; you cannot force or time it
Compare
FinalizationRegistry vs WeakRef, WeakMap and WeakSet
These tools all treat objects weakly, which means they do not keep an object in memory. Only one of them calls you back:
Tool
What it does
Calls you back?
WeakRef
Points to an object without keeping it alive. deref() gives the object, or undefined if it was collected.
No
WeakMap
Stores data under an object key. The entry disappears when the key object is collected.
No
WeakSet
Remembers a group of objects without keeping them alive.
No
FinalizationRegistry
Calls your function after a watched object has been collected.
Yes, later (maybe)
They often work together. A cache can store WeakRef objects and use a FinalizationRegistry to remove the empty entries afterwards. Example 2 shows this.
Behavior
How FinalizationRegistry Works
The registry watches weakly
A registered object is not kept in memory by the registry. If nothing else uses the object, JavaScript is free to delete it.
The callback runs later, never now
JavaScript never calls your cleanup function in the middle of your own code. It runs as a separate task, after the engine has collected the object. That is why every example on this site prints only what happens right away.
It may never run
If the program or the browser tab ends first, or if the engine decides not to collect the object, the callback is simply not called. Do not save data or release locks there.
The held value stays in memory
The registry keeps the held value alive until the callback runs. If the held value points to the watched object, the object can never be collected. Use a string ID or a small number instead.
Cancel with unregister()
When you clean up yourself, call unregister() with the token so the callback does not repeat the work. Example 3 shows the pattern.
Practice
Real-Life Uses
You will rarely need a registry in everyday code. It helps in a few special places:
Use
What the registry does
Cache cleanup
Remove the entry from a Map after the cached object has been collected.
Releasing outside resources
Tell a worker, a canvas or WebAssembly code to free memory after a wrapper object is gone.
Finding memory leaks
Log a message when objects are collected, to check that memory is really freed.
A safety net in libraries
Warn the developer that an object was never closed, while unregister() removes the warning for objects that were closed properly.
Code
JavaScript Examples
Three short programs. Each one prints plain text that is the same every time you run it, because the callback is never part of the output.
Example 1 — Create a Registry and Check the Rules
Create a registry, then break the two rules of the constructor on purpose: the callback must be a function, and new is required.
JavaScript
console.log("typeof FinalizationRegistry: " + typeof FinalizationRegistry);
const registry = new FinalizationRegistry((heldValue) => {
console.log("Cleaned up: " + heldValue);
});
console.log("Created: " + (registry instanceof FinalizationRegistry));
try {
new FinalizationRegistry("not a function");
} catch (err) {
console.log("Callback must be a function: " + err.name);
}
try {
FinalizationRegistry(() => {});
} catch (err) {
console.log("Missing new: " + err.name);
}
Store weakly.cache.set(key, new WeakRef(value)) lets the cache point to an object without keeping it in memory.
Watch with a key.registry.register(value, key) uses the cache key as the held value. After the object is collected, the callback receives the key and can look up the entry.
Clean up safely. The callback deletes the entry only when ref.deref() is empty. Right now both objects are still alive, so the cache has 2 entries and deref() returns both.
Example 3 — Add a Safety Net with unregister()
A TempFile class warns about files that were never closed. Calling close() removes the warning for that file.
JavaScript
const registry = new FinalizationRegistry((name) => {
console.log("Forgot to close: " + name);
});
class TempFile {
constructor(name) {
this.name = name;
this.open = true;
registry.register(this, name, this);
}
close() {
this.open = false;
const removed = registry.unregister(this);
console.log("Closed " + this.name + ", safety net removed: " + removed);
}
}
const draft = new TempFile("draft.tmp");
const backup = new TempFile("backup.tmp");
draft.close();
draft.close();
console.log("backup is open: " + backup.open);
Closed draft.tmp, safety net removed: true
Closed draft.tmp, safety net removed: false
backup is open: true
How It Works
Register every file. The constructor calls registry.register(this, name, this): the file is the target, its name is the held value, and the file is also the token.
Close and cancel.close() calls unregister(this). The first call removes the registration (true). The second call finds nothing (false), so closing twice is harmless.
The net stays for the rest.backup was never closed, so its registration remains. If the object were collected, the callback could print a warning. Never rely on that warning for real cleanup.
Continue
FinalizationRegistry Methods
A FinalizationRegistry has two methods. Each one has its own tutorial:
It is a built-in object that lets you ask for a callback after another object has been garbage collected. You create it with new FinalizationRegistry(callback), watch objects with register(), and cancel with unregister(). It is meant for optional cleanup work.
After the JavaScript engine has deleted a watched object from memory, and never in the middle of your own code. The engine decides when, so it can take a while, and sometimes the callback is not called at all, for example when the program ends first.
Because it is not guaranteed to run. If you save data, close a connection or release a lock in the callback, that work may never happen. Do required cleanup explicitly, for example in a close() method, and use the registry only as an extra safety net.
A WeakRef lets you point to an object without keeping it alive, and you check it yourself with deref(). A FinalizationRegistry calls a function for you after an object has been collected. They are often used together, for example in a cache.
Not from normal JavaScript code. In Node.js you can start the program with the --expose-gc flag and call global.gc() while experimenting, and browser developer tools have a button for it. Even then the callback runs as a separate task, a little later.