Set Object (`Set()`) is a collection of values Which you can iterate like an array and access all the elements in the same order as it inserted.
Set object let you store only unique values of any type like primitive values or object refrence.
It’s syntax look like –
For more detail about set object click here.
Firstly, we create a variable set using the const keyword in which we assign a set object using the new keyword.
const set = new Set();
In the second step, we add some values to set variable.
Now, we checked the value “JS” exists in the set or not. For this, we use a has() method of a set.
console.log(set.has(“JS”)); // output = true
As, we already know that it should return true because we added a “JS” in previous statement.
Finally, we are going to check the size of the set object. Any guess, what is the output of console.
Note : size property exist in Set() not length.
Now, you the answer is 2 but why as we added 3 values not 2. Does it gives a index length like we have in array. Let me explain.
As we have added 3 values in set but according to the definition of Set(). It only stores unique values. That means, when added the “JS” at last it’s neglected.
As we already store the “JS” in our first insertion and in second insertion “Startup“.
So, it only store 2 values in the set.
At last, That’s why we get an answer “2“.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – Reverse array element but in the same position
- JS Quiz – copy object with JSON stringify and parse method
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.