ES2021 introduced two new functionalities to achive the following things

  • How to create an weak references to objects

  • How to run callback before an object is garbage collection?

    The above things can be achieved with below classes introduced in ES2021

    • WeakRef class
    • FinalizationRegistry

WeakRef class

It is an weak reference to an another object without object being garbage collected. another object is called target object.

In javascript, There are two types object references

Weak object reference Strong object reference

In javascript, Whenever you create an object assigned with variable, It creates an memory and variable holds the address of an memory location.

Declare an object and assign the reference

const strongReference = { name:"john",id:1
         };

strongRef variable an reference an employee object . This object will not garbage collect as long as strongRef is pointed.

WeakRef are

    const weakReference = new WeakRef(
        { name:"john",id:1 
        });

Created weak reference to an employee object

During garbage collection running, if there is weak reference to an target object, javascript engine safely remove an target object from memory space is freed.

This will be usefull during websocket communication with short time execution

get an target object from Weakref object

WeakRef class has deref() method which returns target object of an class

WeakRef in javascript features

  • WeakMap and WeakMap are inbuilt javascript weak reference objects
  • Helps to free the space during running garbage collection
  • deref used to get an target object weak reference
  • Target object is not updated Once weakref is created with target object. else undefined can be set
  • It is always suggestable to avoid weakref object if possible

Support in browsers

Please check weakref browser support for browser version support

FinalizationRegistry class

FinalizationRegistry is an class to create an object which runs before garbage collection runs

It is an call back executes when an object is eligible for garbage collection.

Let’s create a call back

let callbackGc=new FinalizationRegistry((value) => {
  console.log("called before GC");
});

Let’s create an object which is eligible garbage collection

let myobject={};

callbackGc.register(myobject,"valuepassed")

when myobject is garbage collected, It runs the callback and print its value