ECMAScript2021 added WeakRef and FinalizationRegistry features to handle garbage collection properly.
Let’s check out these concepts in detail.
We can create a Weak Reference by using new WeakRef,
and can read a reference by calling the
FinalizationRegistry works as a cleaner after the garbage collection. As the memory is reclaimed by the garbage collector, it is needed to be cleaned afterward. FinalizationRegistry works as a cleanup callback.
register(ObjectNeededToBeCleared, heldValue, TokenObject):
Registers target to
this so that cleanup callback will be called.
Unregisters the registered token object and prevents the cleanup callback from happening if the token object is passed inside unregister method parameter.
In the above example, we have unregistered the FakeTokenUnRegisterObject. It will not print the console of that line, instead will keep printing the console of how many seconds it happened to clean up the memory.
The finalization callback does not run immediately after garbage-collection. The timing of garbage collection and finalization callbacks is unspecified. Even though the callback can be useful in some cases, it is advised to avoid it, for important logic or metrics.