ES2021 introduced two new functionalities to achieve the following things
How to create a weak reference to objects
How to run a callback before an object is garbage collected?
The above things can be achieved with the below classes introduced in ES2021
- WeakRef class
- FinalizationRegistry
WeakRef class in javascript
It is a weak reference to another object without the object being garbage collected. another object is called a target object.
In JavaScript, There are two types of object references.
Weak object reference Strong object reference
In JavaScript, Whenever you create an object assigned with a variable, It creates a memory, and the variable holds the address of a memory location.
Declare an object and assign the reference.
const strongReference = { name:"john",id:1
};
strongRef variable is a reference to an employee object. This object will not be garbage collected as long as strongRef is pointed.
WeakRef
are
const weakReference = new WeakRef(
{ name:"john",id:1
});
A created weak reference to an employee object
During garbage collection running, if there is a weak reference to a target object, the javascript engine safely removes a target object from memory space.
This will be useful during WebSocket communication with short-time execution.
Get a target object from Weakref object in javascript
WeakRef class has the deref()
method which returns the target object of a class.
WeakRef in javascript features
- WeakMap and WeakMap are inbuilt javascript weak reference objects
- Helps to free space during running garbage collection
deref
used to get a target object’s weak reference- The target object is not updated Once weakref is created with the target object. else undefined can be set
- It is always suggestible to avoid weakref objects if possible
Support in browsers
Please check weakref browser support for browser version support
FinalizationRegistry class in javascript example
FinalizationRegistry
is a class to create an object that runs before garbage collection runs
It is a callback that executes when an object is eligible for garbage collection.
Let’s create a callback
let callbackGc=new FinalizationRegistry((value) => {
console.log("called before GC");
});
Let’s create an object which is eligible for garbage collection.
let myobject={};
callbackGc.register(myobject,"valuepassed")
when myobject is garbage collected, It runs the callback and prints its value.