javascript
  1. javascript-set

JavaScript Set

The JavaScript Set is a built-in object that allows you to store a collection of unique values and iterate over the set elements in the order of insertion. This means that every value in the set must be unique, and it can be of any data type.

Syntax

To declare a set, you can use the Set() constructor function as follows:

const mySet = new Set();

You can also create a set from an array using the spread operator. The elements of the array will be the values of the set:

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

Example

const mySet = new Set();
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
console.log(mySet); // Output: Set { 'apple', 'banana', 'orange' }

Output

In the example above, we are creating a new set, adding three elements to it, and then logging it to the console. The output is a Set object with the elements apple, banana, and orange.

Explanation

The add() method is used to add elements to the set. If the element already exists in the set, then it will not be added again, because sets can only contain unique values. We can also add elements to a set during its initialization.

Use

Sets are useful in situations where you need to store unique values, such as removing duplicates from an array or checking if a value is already present in a collection. You can iterate over the elements of the set using the forEach() method or using a for ... of loop.

Important Points

  • Sets only contain unique values.
  • The add() method is used to add elements to a set.
  • The has() method is used to check if a value is present in the set.
  • The delete() method is used to remove elements from the set.
  • You can get the length of a set using the size property.

Summary

In summary, the JavaScript Set is a built-in object that allows you to store a collection of unique values. You can add and remove elements to and from the set, and iterate over the elements in the order of their insertion. Sets are useful in situations where you need to store unique values and check if a value is already present in a collection.

Published on: