Home

FinalizationRegistry

FinalizationRegistry is a JavaScript built-in that enables running cleanup logic after an object becomes unreachable and is garbage collected. It works with weak references to avoid keeping objects alive.

A FinalizationRegistry is created with a cleanup callback: new FinalizationRegistry((heldValue) => { ... }). You register a target object by

Important semantics: finalization is non-deterministic and not guaranteed to occur in a timely manner. The callback

Common use: associating external resources (such as native handles) with a JavaScript object and releasing them

Compatibility: FinalizationRegistry was introduced in ES2021 and is supported in all major modern browsers and in

calling
registry.register(target,
heldValue,_unregisterToken).
When
the
target
is
garbage
collected,
the
runtime
will
enqueue
the
cleanup
with
the
corresponding
heldValue
so
the
callback
can
perform
resource
cleanup
or
bookkeeping.
The
optional
unregisterToken
allows
you
to
detach
a
target
before
collection
by
calling
registry.unregister(unregisterToken).
may
run
much
later,
or
not
at
all
if
the
process
exits.
It
must
not
be
used
for
guaranteed
resource
release,
and
the
target
must
not
be
depended
on
during
finalization.
Avoid
re-referencing
the
target
in
the
finalization
callback;
do
not
attempt
to
resurrect
it.
when
the
object
is
GC’d.
It
is
often
used
with
WeakRef-based
patterns
to
manage
non-memory
resources.
Node.js
14
and
later.