JavaScript Set Creating a Set


The Set object lets you store unique values of any type, whether primitive values or object references.

You can push items into a set and iterate them similar to a plain JavaScript array, but unlike array, you cannot add a value to a Set if the value already exist in it.

To create a new set:

const mySet = new Set();

Or you can create a set from any iterable object to give it starting values:

const arr = [1,2,3,4,4,5];
const mySet = new Set(arr);

In the example above the set content would be {1, 2, 3, 4, 5}. Note that the value 4 appears only once, unlike in the original array used to create it.