Sobes.tech
Middle+

What is a weak reference in JavaScript?

sobes.tech AI

Answer from AI

Weak reference — is a reference to an object that does not prevent the garbage collector from deleting that object if there are no other "strong" references to it. If the object is deleted, the weak reference becomes invalid. The main use cases are caching objects related to other objects or implementing weak collections (e.g., WeakMap, WeakSet).

In JavaScript, weak references are implemented through:

  • WeakMap: A key-value collection where keys are objects (referenced weakly), and values can be anything. If a key is garbage collected, the corresponding key-value pair is also removed from the WeakMap.
  • WeakSet: A collection of objects referenced weakly. If an object is garbage collected, it is also removed from the WeakSet.
  • WeakRef: Allows creating a weak reference to any object. You can attempt to get the value of the weak reference using the .deref() method. If the object has been deleted, .deref() returns undefined.

Example of using WeakMap:

// Create an object to be used as a key
let myObject = { id: 1 };

// Create a WeakMap
const myWeakMap = new WeakMap();

// Add a pair to the WeakMap using myObject as the key
myWeakMap.set(myObject, 'some value');

// myObject is garbage collected (e.g., after myObject = null;)
// The pair { myObject: 'some value' } will automatically be removed from myWeakMap

Example of using WeakRef:

// Create an object
let data = { value: 'hello' };

// Create a weak reference to the object
const weakRef = new WeakRef(data);

// Get the value of the weak reference (the data object)
console.log(weakRef.deref()); // { value: 'hello' }

// data = null; // The "strong" reference to the object is removed

// After some time (not immediately), the object may be garbage collected

// Attempt to get the value again: may return undefined
// console.log(weakRef.deref()); // undefined (if the object has been collected)

These mechanisms are useful for memory management in scenarios where objects reference each other but should not prevent garbage collection when no other references exist.

What is a weak reference in JavaScript? — Node.js - sobes.tech