JavaScript FinalizationRegistry

Beginner
8 min read
Updated: Nov 2026
3 examples
Memory cleanup

Definition and Usage

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().

This page explains the idea. The FinalizationRegistry Methods index links the full guides for register() and unregister().

Cleanup is a bonus, not a promise.

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.

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

Core Ideas

Ideas every FinalizationRegistry tutorial in this series builds on:

IdeaExampleRemember
Registrynew FinalizationRegistry(callback)Holds the cleanup function and the list of watched objects
Targetregistry.register(obj, "id")The object to watch; the registry does not keep it alive
Held valueregistry.register(obj, "id")Given to the callback later; it must not be the target
Unregister tokenregistry.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 collectionautomaticThe engine frees unused objects; you cannot force or time it

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:

ToolWhat it doesCalls you back?
WeakRefPoints to an object without keeping it alive. deref() gives the object, or undefined if it was collected.No
WeakMapStores data under an object key. The entry disappears when the key object is collected.No
WeakSetRemembers a group of objects without keeping them alive.No
FinalizationRegistryCalls 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.

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.

Real-Life Uses

You will rarely need a registry in everyday code. It helps in a few special places:

UseWhat the registry does
Cache cleanupRemove the entry from a Map after the cached object has been collected.
Releasing outside resourcesTell a worker, a canvas or WebAssembly code to free memory after a wrapper object is gone.
Finding memory leaksLog a message when objects are collected, to check that memory is really freed.
A safety net in librariesWarn the developer that an object was never closed, while unregister() removes the warning for objects that were closed properly.

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);
}

How It Works

  1. It is a constructor. FinalizationRegistry is a built-in class, so typeof says "function", and new FinalizationRegistry(callback) creates a registry.
  2. The callback must be a function. Passing a string throws a TypeError, because there would be nothing to call later.
  3. Use new. Calling FinalizationRegistry(...) without new also throws a TypeError.

Example 2 — Build a Small Cache with WeakRef

A cache stores each object behind a WeakRef. The registry gets the cache key as the held value, so it can delete empty entries later.

JavaScript
const cache = new Map();

const registry = new FinalizationRegistry((key) => {
  const ref = cache.get(key);
  if (ref && !ref.deref()) {
    cache.delete(key);
  }
});

function addToCache(key, value) {
  cache.set(key, new WeakRef(value));
  registry.register(value, key);
}

const alice = { name: "Alice" };
const bob = { name: "Bob" };

addToCache("user-1", alice);
addToCache("user-2", bob);

console.log("Cache size: " + cache.size);
console.log("user-1: " + cache.get("user-1").deref().name);
console.log("user-2: " + cache.get("user-2").deref().name);
Methods index

How It Works

  1. Store weakly. cache.set(key, new WeakRef(value)) lets the cache point to an object without keeping it in memory.
  2. 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.
  3. 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);

How It Works

  1. 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.
  2. 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.
  3. 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.

FinalizationRegistry Methods

A FinalizationRegistry has two methods. Each one has its own tutorial:

MethodWhat it does
register()Watch an object, choose the held value, and add an optional unregister token.
unregister()Cancel registrations with a token. Returns true or false.

Full list: FinalizationRegistry Methods index.

Frequently Asked Questions

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.

Browse the FinalizationRegistry methods

Open the index for register() and unregister(): syntax, runnable examples, and FAQs.

FinalizationRegistry Methods index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful