in operator –
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.
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.
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);
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.
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 –
- JS Quiz – Did really the reference pass using Array.from() 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.