WeakSet in JavaScript

WeakSet in JavaScript

Understanding weak references

In this article, you will get to know about how we can use a weakset with the help of some examples.

But first what exactly is a weak reference?

Unlike a strong reference, A weak reference is a reference from which a referenced object does not get secured by a collection of a garbage collector.

A strong or a normal reference would stop the garbage collection of an object even if it is the only object referencing it. Let's put these definitions into account with an example below:

// Strong reference 

let fruit = { name: "apple" };

const food = [fruit];

fruit = null;

console.log(food); // [{ name: "apple" }]

// Weak reference

let food = new WeakMap();
let fruit = { name: "apple" };

food.set(fruit, "something");
console.log(food);  // WeakMap{ {...} -> "something" } <= fruit set to the WeakMap

fruit = null;  // Overwrite the reference to the object
console.log(food);  // WeakMap(0) <= fruit has been garbage collected.

While the normal reference to the fruit object still is in existence, we get to see from the above example that the fruit object persists in the WeakMap and we can access it furthur. But when we try to override the fruit object by reassigning it to null, the weak reference coming from the WeakMap object becomes the only reference to the original object in memory.

So because it's a weak reference, it won't stop the garbage collection from occurring. This also denotes that when the garbage collector gets executed again by the JavaScript Engine, the fruit object will be deleted from the memory and the WeakMap we designated to it.

WeakSet

Synonymously, a weakset is same as a set. They were introduced in ES6 and we can only use objects in a weakset, unlike a set which can include numbers, strings, objects, etc. Let's see with an example:

let set = new WeakSet();
console.log(set);  // WeakSet {}

let greetings = {
    message: 'Hello',
    sendMessage: true
}

set.add(greetings);
console.log(set); // WeakSet {{message: "Hello", sendMessage: true}}

One thing to note about weaksets is that they are not iterable. Example:

const set = new WeakSet( {x:1} );

// looping through a WeakSet
for (let i of set) {
    // TypeError
    console.log(i);
}

Conclusion

WeakSet would be an ultimate go-to choice if we need to store some additional data for a short period of time and don't need to worry about how the objects are deleted. Also, its not a possible case that we need to use weaksets and references judiciously in JavaScript. It's nice to be knowledgeable about them, but majorly it's always recommended to use strong references. Consider referring this for the methods and other use cases applied on a weakset.