WeakRef's 101

In 2021 MDN launched a new javascript API, WeakRef, now as the name suggests, weakref is something that creates a weak reference around something, but to whom ? weakref only holds a weak reference to an javascript object, that is JavaScript engine's will not avoid the garbage collector from collecting the particular if that object has no other strong reference to it, while on the other hand a strong/normal reference will avoid the object from being garbage collection, the potential problem it addresses is memory wastage/leaks, (as a object holds a normal/strong the object will not be garbage collected) hence the object stays there.

const obj={
name: 'Raunak',
age: '23',
}

let weakRef= new WeakRef(obj) 
//here we have created a reference which holds a weak reference around the "obj"

The WeakRef() constructor gives us the method in return that is "deref()", this deref method can return us the referent object (the object around which reference was made) or it will return us undefined

console.log(weakRef.deref())
/*
Output
{name:"Raunak",
age:"23"
}
*/

the case where it returns undefined is because that object has been garbage collected, hence it is a good practice to always place a condition after derefing the value. Also the deref may never return undefined, even if there's no strong reference to the object, because deref will only return undefined if the particular object is garbage collected and the process of garbage collection is undetermine to us as different engine do it differently. This al-together takes us to garbage collection, it's a process where the objects are who are not referenced arebeing marked and after marking is completed, the marked object are being deleted.

notes about WeakRef

  • 1 Object can have multiple weak references, but they will be always in sync, meaning if 1 deref is called, it will return the same the value, that the other deref will return.
  • The referent object/ target object will never change, it will always be the same (the original one)