JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – can in operator check value or index in an array

JavaScript Quiz – can in operator check value or index in an array

in operator –

The in operator returns true if given property or key is in the specified object or its prototype chain. Its syntax looks like.

prop in object

For detailed information about in operator click here.

JavaScript Question

In this javascript quiz, you need to find out the output of the console log in which we use in the operator to check 1 exist in the array.

In the first step, we declare an array using let keyword and assign an array to it which contain 2 elements.

let myArray = [‘JS’, ‘Startup’, ‘Like’];

In the next step, we just write an myArray with index one.

myArray[1];

Finally, we console log the statement with in operator to check the 1 exist in myArray variable. Any idea what’s the output of the below statement.

console.log(‘1’ in myArray);

Answer – true

Click To Run Code

Explanation

Now, you know the answer is true, but why let me explain.

So, the second statement in which we are accessing the index 1 of myArray variable. It’s just to make you confuse as it just like accessing an value of myArray with index 1.

myArray[0];

Now, the main part as we are checking that 1 exists in myArray variable but my array only contains 3 elements which are as follows.

[‘JS’, ‘Startup’, ‘Like’]

Then, the answer should be false but why it’s true. Did you read in operator definition? It check for property or key not the values.

So, obviously myArray has 3 element at index 0, 1, 2 and property 1 exist in array.

That’s why we get an answer “true“.

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. JavaScript Quiz – what is really object entries method return
  2. JavaScript Quiz – Did really string substring method can do this
  3. JS Quiz – Did really the reference pass using Array.from() method
  4. JavaScript Quiz – Is the String() and toString() are really same

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