Set

In JavaScript, a Set is a built-in data structure that represents an ordered collection of unique values. It is similar to an array, but with a few key differences. Here are some details about the Set data type:

  1. Unique values: Sets only store unique values, meaning there can't be any duplicates. If you try to add a value that already exists in the Set, it will be ignored.

  2. Order: Like arrays, Sets maintain the order of the elements that are added to them. However, unlike arrays, there is no numerical index associated with each element in a Set.

  3. Methods: Sets have a variety of methods that can be used to add, remove, and check for the existence of elements. Some of these methods include add, delete, has, and clear.

  4. Iteration: Sets can be iterated over using a for...of loop, making it easy to perform operations on each element in the Set.

Here's an example of how to create a Set and add elements to it:

const mySet = new Set();

mySet.add('apple');
mySet.add('banana');
mySet.add('cherry');
mySet.add('banana'); // Ignored because 'banana' already exists in the Set

console.log(mySet); // Output: Set { 'apple', 'banana', 'cherry' }

Sets can be a useful data structure in situations where you need to store a collection of unique values and perform operations on them efficiently.

Last updated