Set in JavaScript,

Set in JavaScript,

In JavaScript, a set is a built-in object that allows you to store a collection of unique values. The Set object is similar to an array, but unlike an array, it can only contain unique values. In other words, you can't have two elements with the same value in a set. In this article, we'll explore the set in JavaScript, including its methods and examples.

Creating a Set To create a new set, you can use the Set() constructor or the new Set() syntax. Here's an example:

const set1 = new Set();
const set2 = new Set([1, 2, 3]);

The first line creates an empty set, while the second line creates a set with three elements.

Adding and Removing Elements To add an element to a set, you can use the add() method:

set1.add(1);
set1.add(2);
set1.add(3);

This adds the values 1, 2, and 3 to set 1. You can also add multiple values at once using the spread operator:

set1.add(...[4, 5, 6]);

To remove an element from a set, you can use the delete() method:

set1.delete(1);

This removes the value 1 from set 1.

Checking for the Presence of Elements You can check if a set contains an element using the has() method:

set1.has(2); // returns true
set1.has(10); // returns false

Iterating over a Set You can use a for...of loop to iterate over the elements in a set:

for (const item of set1) {
  console.log(item);
}

This will output each element in set 1.

You can also use the forEach() method to iterate over the elements in a set:

set1.forEach(item => console.log(item));

This will also output each element in the set1.

Getting the Size of a Set To get the number of elements in a set, you can use the size property:

set1.size; // returns 5

Combining Sets You can combine two sets using the union operator (|):

const set3 = new Set([...set1, ...set2]);

This creates a new set that contains all the elements in set1 and set2.

You can also use the intersection operator (&) to create a new set that contains only the elements that are in both sets:

const set4 = new Set([...set1].filter(x => set2.has(x)));

This creates a new set that contains only the elements that are in both set1 and set2.

Conclusion

In conclusion, the Set object in JavaScript allows you to store a collection of unique values. You can add and remove elements, check for the presence of elements, iterate over the elements, and combine sets. The Set object is a useful tool in JavaScript for working with unique values.