Finalizer

A FinalizationRegistry object, added alongside WeakRef in ECMAScript 2021, lets you request a callback (a 'finalizer') to be scheduled after a registered object has been garbage-collected. Register an object with .register(target, heldValue [, unregisterToken]), where heldValue is passed to the callback (and must not itself strongly hold target, or it can never be collected). Call .unregister(unregisterToken) to cancel a registration before collection happens.


const registry = new FinalizationRegistry((heldValue) => {
  console.log('cleaned up:', heldValue);
});

(function () {
  let obj = {name: 'temporary'};
  registry.register(obj, 'temporary', obj);   // obj itself is the unregisterToken here
  // registry.unregister(obj);   // would cancel the callback above
})();

cleaned up: temporary (logged at some later, unspecified point -- if at all -- once the engine actually collects the object)

As with WeakRef, finalizer callbacks run at an unspecified time (or possibly never), must not be relied upon for program correctness (eg. do not use them to release a lock or close a file handle that matters right now), and exist mainly as a diagnostic and memory-management aid.