0

Hi I am New to JS i trying below code

a=[0,1,3]
if (2 in a){ console.log(a)}

in above code i am checking element is available are not. but in above case 2 is not in array but condition show true why?

i know we can check condition like this a.includes(2) why in above case showing true?

Thanks Advance.

  • 3
    [_"The in operator returns true if the specified property is in the specified object or its prototype chain."_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in). Here, the key "2" is a property of this Array (it's the index of the value "3") – blex Mar 30 '20 at 09:49
  • 1
    0xc14m1z's answer is correct - what you need to use is `a.indexOf(2) !== -1` for checking if `2` is in `a`. be careful using `.includes()`, it's not supported in IE – andy mccullough Mar 30 '20 at 09:51

1 Answers1

5

Becase the in operator checks whether a property is defined in an object.

The array indexes are the "properties" of the array objects, thus, the 2 property is the index 2, which contains the value 3.

0xc14m1z
  • 3,675
  • 1
  • 14
  • 23