JAVASCRIPT SETS
Tags: webdev, javascript, programming, beginners
Published: 2023-11-14 15:42:02

## **<u>INTRODUCTION</u>**

JavaScript Sets are an excellent tool for maintaining a set of distinct values. They are very different from arrays, despite the fact that they both store values.

You can store unique values of any kind, including object references and primitive values, using the Set object.

Here, uniqueness is the crucial word. A Set only returns unique values, as we will see in a moment, even if we load it with non-unique data.

The syntax;

```
new Set([iterable]);
```

If you wish to start using sets in your code, you should become familiar with some of their built-in methods. I'll walk you through everything quickly and demonstrate how to use it so you can begin working right away.


## **<u>CREATING A SET</u>**

All you need to do to build an empty set is to use the Set() constructor and the term "new," as demonstrated below.

```
let mySet = new Set();
```

## To add elements to a set, use the Set.add() method:


```
Let mySet = new Set();
mySet.add(5);
console.log(mySet); // Set(1)&nbsp;{5}
```
You can add objects, numbers, strings, or any other type of data you want to add to sets. The same value will only show up in the set once if you attempt to add it twice:


```
let mySet = new Set();
mySet.add(5);
mySet.add(5);
console.log(mySet); // Set(1)&nbsp;{5}
```



## Eliminating components from a Set



The Set.delete() method in Javascript can be used to remove a single element from a set:

```
let mySet = new Set();
mySet.add(5);
mySet.delete(5);
console.log(mySet); // Set(0)&nbsp;{}
```

In order to remove every item from a set, you may also utilize the Set.clear() method:

```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.clear();
console.log(mySet); // Set(0)&nbsp;{}
```

📌 Taking items out of a Set

It's noteworthy to note that objects are still created with independent references, thus the Set.delete() method cannot be used to remove an item from a set. Even when this is attempted, the object item continues to show up in the set:

```
let mySet = new Set();
mySet.add({o: 4});
mySet.delete({o: 4});
console.log(mySet); // Set(1)&nbsp;
```

Alternatively, you must use forEach or a similar looping technique to remove an object from a set. Once you've located the element you wish to remove, just remove it normally:

```
let mySet = new Set();
mySet.add({o: 4});
mySet.forEach((x) => { 
    if(x.o == 4) {
        mySet.delete(x)
    }
});
console.log(mySet); // Set(0)&nbsp;{}
```



## Set entries and keys


Since sets don't actually have keys, as I sort of said, Set.entries() is quite peculiar. The entries() method in Javascript usually returns the key-value pairs in an array format, such as [key, value], from a data structure. Set.entries() just gives the same result for both key and value because sets don't have keys. This method's primary purpose is to maintain consistency with the Map data type:

```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
let setEntries = mySet.entries();

for(let x of setEntries) {
    console.log(x);
    // Returns [ 5, 5 ], [ 10, 10 ]
}
```
📌 Checking Set Membership

In JavaScript, the primary application of sets is membership checking. Compared to using something like Array.includes(), this is somewhat faster. The Set.has() method can be used to verify set membership. If the item is present in the set, it returns true; otherwise, it returns false.


```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
console.log(mySet.has(10)); // true
```

Once more, this will not function with objects precisely because, when verified with has, an object has a different reference. As a result, you must loop around an object and verify a value within the object to determine if it is part of a set:

```
let mySet = new Set();
mySet.add({o: 4});
mySet.forEach((x) => { 
    if(x.o == 4) {
        // the object is in the set
    }
});
```
📌 Determining a set's size

Sets have.size, but arrays have.length. We are unable to use.length, as we would typically do, to determine the size or length of a set. Rather,.size: is used to determine a set's size.

```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
console.log(mySet.size); // Returns 3

```

📌 Iterating over a Set

A basic for loop can be used to loop through sets themselves:

```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
for(let x of mySet) {
    console.log(x); // Returns 5, 10, 20
}
```

On the other hand, you may also utilize the forEach() method that is tied to sets. However, loops are generally faster:

```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
mySet.forEach(() => {
    console.log(x); // Returns 5, 10, 20
}
```
Furthermore, sets include an iterator function connected. You may use next() to cycle through each item in a set after accessing it as demonstrated in the code below. Iterator methods are present in a lot of data structures and prototypes, even if you may not have seen them before. Here, `mySet[Symbol.iterator]()` is used to access it.

```
let mySet = new Set();
mySet.add(5);
mySet.add(10);
let setIterator = mySet[Symbol.iterator]();

console.log(setIterator.next()); // Returns { value: 5, done: false }
console.log(setIterator.next()); // Returns { value: 10, done: true }
```

📌 Javascript sets are a really fascinating and rarely used data structure that provide us with an effective way to determine whether an item is a part of another set of objects. They serve a very specialized purpose and resemble arrays in certain ways.