ES6 Set vs WeakSet vs Arrays – Describing the differences

If you have used languages like Ruby, Python or Java, surely you have interacted with Set. Set has been introduced to JavaScript little late, in 2015, version 6 (ES6). The inclusion of Set & WeakSet has increased the efficiency of data storing & flexibility of JS. In this article I will be taking you on a short tour of Set and WeakSet.

Set

What is Set?

Using the Set class you can create an array like heterogeneous iterable object, which will contain only unique values in it. Unique is not just unique by values but also by types. i.e. it will consider "2" and 2 separate or different. In case of objects; two objects having the same properties and values will not be considered similar; but only the ones with same memory address will.

Syntax:

Set Examples

Hope the examples have given you a clear view on Sets and you may have also find similarities of Set with JavaScript Array. So, below is the table to differentiate between them.

Set vs Array

Array Set
Contains whatever value you push Contains only unique values
Focused to index. You need to write code to find and delete a particular element Focused to value. You can delete a value easily
.push() to add an element .add() to add an element
.includes() (ES7) to find if an element is there in an array .has() to find if an element is there in a set
.length to find how many elements .size to find number of elements
arr.splice(0,arr.length) to empty an array mySet.clear() to clear a Set

WeakSet

What is WeakSet

Now that you know about set, it will be easier to pick WeakSet from here. If you have read our Map vs WeakMap article, you could have already started guessing what is the difference.
In short, a WeakMap is a collection similar to Set, which holds unique values; but it only holds Objects and nothing else. If an object which is there in your WeakSet object has no other reference variable left, it will automatically be deleted.

Syntax:

WeakSet Examples

As you can see, no primitive values can be added to WeakSet. It only accepts objects. Functionalities and methods are very similar to Set, but it will auto delete that object from the list which has no other reference left.

Set vs WeakSet

Set WeakSet
Can contain any type of values Can only contain objects
To find number of elements use .size To find elements count use .length
.forEach() is available to iterate No .forEach() to iterate
Nothing is auto destroyed If an element object has no other reference left, it will be auto released to garbage collector
About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.