Frontend Mayhem

JavaScript : Set vs WeakSet

October 22, 2018

Arrays & Sets Image

If you aren’t familiar with Set in JavaScript then I recommend reading this blog post before learning the difference between Set & WeakSet. Both Set & WeakSet are key-based collections but with some crucial differences.

Just like Set, the WeakSet constructor takes in an iterable object as input. The main difference is that WeakSet can only contain objects & not any other type.

const mySet = new WeakSet(); // Initializes an empty weak set

// Difference between the Set & Weak Set

// Initializes a set with 3 values { 1, 2, 3 }
const mySet2 = new Set([1, 2, 3, 3]);

// The same syntax doesn't work for WeakSet
// Throws an error because we're using primitive values
const mySet2 = new WeakSet([1, 2, 3, 3]);

// The correct way to initialize a WeakSet
const helloWorld = { hello : 'world' };
const mySet3 = new WeakSet([helloWorld]);
console.log(mySet3.has(helloWorld)); // true

Weak vs Strong References

The other main difference between the two is that references to objects in a WeakSet are held “weakly”. This means that if there is no other reference to an object in the WeakSet it will get garbage collected. The same is not true for Set. An object stored in a Set will not be garbaged collected even if nothing is referencing it.

This distinction is important because for this reason there is no way to access or iterate over objects stored inside a WeakSet. We also don’t have access to the size of the weak set for this same reason.

WeakSet exposes only three methods

add - appends a new object to the weak set

delete - deletes the new object from the weak set

has - returns a boolean after checking if an element with the same value exists in the weak set.


Watandeep Sekhon

Written by Watandeep Sekhon.
Website / Twitter / LinkedIn / Instagram