JavaScript Set is a collection of unique values. It can be used to store data in a more structured way than JavaScript Array object.
A Set object can be created using new Set()
constructor. It takes an iterable as an argument (array, map, etc.) and creates a set from it.
const mySet = new Set([1, 2, 3]);
console.log(mySet); // Set { 1, 2, 3 }
The above code creates a set from an array. The order of elements in the set is the same as the order of elements in the array. However, if we add duplicate values to the set, only one instance of the value will be stored:
const mySet = new Set([1, 2, 3]);
mySet.add(3); // only one instance of 3 will be added to the set
console.log(mySet); // Set { 1, 2, 3 }
We can also initialize a set with no arguments:
const mySet = new Set();
This creates an empty set.
We can add elements to this set using add()
method:
mySet.add(1);
console.log(mySet); // Set { 1 }
If we try to add a duplicate value to the set, it will not be added:
mySet.add(1);
console.log(mySet); // still displays Set { 1 }
To check if a value exists in a set, we can use has()
method:
console.log(mySet.has(1)); // true
console.log(mySet.has('a')); // false
To remove an element from a set, we use delete()
method:
mySet.delete('a');
console.log(mySet); // Set { 1 }
To get the number of values in a set, we use size
property:
console.log(mySet.size); // 1
We can loop through all values of a set using forEach()
method:
mySet.forEach(value => { console.(value) });
This will display each value on a separate line.
Note that sets are not ordered like arrays and we cannot access elements by their index numbers using square brackets notation ([]) like we do with arrays because sets are not indexed collections.