The Set class

A set is a collection of unordered unique values. In JavaScript you create a set by using the Set() constructor with the argument that can be any iterable object.

let s = new Set(); // Empty set
let s2 = new Set([1, s]); // A set with two memebers
let sCopy = new Set(s2); // A set with elements copied from s2
let uniqueLetters = new Set('Mississippi'); // 4 elements: 'M', 'i', 's', and 'p'

You can add and remove elements with add(), delete(), and clear() methods. The size property returns the number of elements in the set. The add() method returns the set it is invoked on, so it is possible to add multiple values to the set by using a chained method. The membership is based on strict equality === checks.

s.add(1); // Add a number to the set
s.add(true); // Add a boolean to the set
s.add([1,2,3]); // Add an array to the set
s.add('a').add('b').add('c'); // Add multiple values in chain
s.size; // => 6
s.delete(1); // => true
s.delete('test'); // => false: 'test' is not a member of the set
s.delete(true); // => true
s.delete([1,2,3]); // => false: array in the set is different
s.clear(); // remove everything in the set
s.size; // => 0

The has() method checks whether a specified value is a member of the set. Sets are optimized for membership testing, so it is very fast even for very large sets.

let primes = new Set([2,3,5,7]);
primes.has(2); // => true
primes.has(3); // => true
primes.has(4); // => false
primes.has('5'); // => false

The Set class is iterable, therefore you can use a for/of loop to enumerate all of the elements in a set. The iteration remembers the order that the elements were inserted in, so the first inserted element will be the first one appearing in the iterated sequence, and the most recently inserted showing up the last one in the sequence.

let sum = 0;
for (let p of primes) {
  sum += p;
sum; // => 17

You can also convert sets to arrays and argument lists with the spread operator ....

[...primes]; // => [2, 3, 5, 7]
Math.max(...primes); // => 7

The Set class also implements a forEach() method. Unlike the array method of the same name, forEach() in sets does not pass the index as the second argument to the argument function.

let product = 1;
primes.forEach(n => { product *= n; });
product; // => 210