Why does the "in" operator in Javascript return true when testing if "0" exists in array, even when the array doesn't appear to contain "0"?
For example, this returns true, and makes sense:
var x = [1,2]; 1 in x; // true
This returns false, and makes sense:
var x = [1,2]; 3 in x; // false
However this returns true, and I don't understand why:
var x = [1,2]; 0 in x;
The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.
Using in with deleted or undefined propertiesIf you set a property to undefined but do not delete it, the in operator returns true for that property. The in operator will return false for empty array slots. Even if accessing it directly returns undefined .
just like the js for in loop which iterates the object properties, the in operator checks if the specified property is in the specified object or its prototype chain. it does not check whether an element is in an array.
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.
It refers to the index or key, not the value. 0
and 1
are the valid indices for that array. There are also valid keys, including "length"
and "toString"
. Try 2 in x
. That will be false (since JavaScript arrays are 0-indexed).
See the MDN documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With