Set in JavaScript

In JavaScript, a Set is a collection of unique values of any type, which means that each value can occur only once in the Set. It can be used to store a collection of values without any duplication.

To create a Set in JavaScript, we use the Set() constructor or the Set literal notation by enclosing the values in curly braces {} separated by commas. Here are some examples:

// creating a set using Set() constructor
const mySet = new Set(); 

// adding values to the set using add() method
mySet.add(1);
mySet.add(2);
mySet.add(3);

// creating a set using Set literal notation
const mySet2 = new Set([1, 2, 3, 3]);

console.log(mySet); // Set {1, 2, 3}
console.log(mySet2); // Set {1, 2, 3}

In the above example, we first created an empty Set using the Set() constructor and then added values to it using the add() method. We then created another Set using the Set literal notation, which automatically removes duplicates, so the second Set only contains the unique values 1, 2, and 3.

Sets also have various built-in methods for performing operations on the set such as has(), delete(), clear(), size(), forEach(), entries(), values(), and keys().

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

// check if set contains a value
console.log(mySet.has(2)); // true

// remove a value from set
mySet.delete(3);

// get size of set
console.log(mySet.size); // 3

// loop through set using forEach
mySet.forEach((value) => console.log(value));

// get values from set
console.log(mySet.values()); // SetIterator {1, 2, 4}

In the above example, we first created a Set with values [1, 2, 3, 4], then used the has() method to check if the set contains a value (2), deleted a value (3) from the set using delete(), obtained the size of the set using size, looped through the set using forEach, and finally obtained the values of the set using values().

In summary, a Set is a useful data structure in JavaScript that allows you to store a collection of unique values of any type, perform various operations on the set, and avoid duplications.

For more information, refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Leave a comment

Your email address will not be published. Required fields are marked *