FrontendDeveloper.in

ECMAScript question detail

WeakRef

WeakRef provides two new pieces of functionality

  1. creating weak references to objects with the WeakRef class
  2. running user-defined finalizers after objects are garbage-collected, with the FinalizationRegistry class

WeakRef: weak reference is a reference to an object that doesn’t prevent garbage collection if it is the only reference to the object in the memory.It’s useful when we don’t want to keep the object in memory forever(e.g, WebSocket). The main use of weak references is to implement caches or mappings to large objects for which you don't need to keep it in memory for rarely used objects.

Prior to ES12, WeakMaps and WeakSets are the only way to kind-of-weakly reference an object in JavaScript. Whereas WeakRef in ES12 provides actual weak references, enabling a window into the lifetime of an object.

Let's see an example of a weak reference object using WeakRef constructor and read the reference using deref() method

const myObject = new WeakRef({
name: ‘Sudheer’,
age: 34
});
console.log(myObject.deref()); //output: {name: “Sudheer”, age: 35}
console.log(myObject.deref().name); //output: Sudheer

Finalizers: A FinalizationRegistry object lets you request a callback when an object is garbage-collected. It works as a cleanup callback.

// Create new FinalizationRegistry:
const reg = new FinalizationRegistry((val) => {
console.log(val);
});

(() => {
// Create new object:
const obj = {}

// Register finalizer for the "obj" as first argument and value for callback function as second argument:
reg.register(obj, 'obj has been garbage-collected.')
})();

Note: The finalization callback does not run immediately after garbage-collecting the event listener, so don't use it for important logic or metrics.

Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399