JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – new set object can return the same size

JavaScript Quiz – new set object can return the same size

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 –

Set()

For more detail about set object click here.

JavaScript Question

In this javascript quiz code, you need to find out does new set object return the same size as 3 value added in the set object.

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.

set.add(“JS”).add(“Startup”).add(“JS”);

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.

console.log(set.size);

Note : size property exist in Set() not length.

Answer – 2

Click To Run Code

Explanation

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 –

Check out our other javascript quiz – 

  1. JS Quiz – Reverse array element but in the same position
  2. JavaScript Quiz – filter array method based on the element size
  3. JS Quiz – copy object with JSON stringify and parse method
  4. JavaScript Quiz – can isFrozen method really check freeze object

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top
0 Shares
Share via
Copy link