Sets in JavaScript

Sets in Javascript

In an array, we have seen that we can store multiple values together, using the arrays. But those multiple values can be duplicated as well, which means that we are allowed to have duplicate values in our arrays. But, if we do not want duplicate values, in short, if we want to have unique values of some type, we can make some sets in this case.

So, let’s have a look at how can we create a set in JavaScript. Creating a set is very easy. Let’s see how are we going to create a set –

So, as you can see, from line 1, we have created a set. The documentation says that a set is an object that lets you store unique values of any type. This explains why are we using the new keyword.

Now, when we try to have a look at the output into the console, it appears to be something like this –

As you can see, the set got created. This is a different thing, that it is empty right now. But we could create the set anyways. Now, you might have an obvious question at this point, Is that ok…

we have created the set now, but…

how about adding some elements to that set?

How are we going to do that?

Well, it is very easy, and there are multiple ways to achieve this too. First of all, while creating the set in the above example, we made use of the Set() constructor. To this constructor, we can pass something iterable (iterable means something through which we can iterate, like an array, or a string for example).