Why does javascript's "in" operator return true when testing if 0 exists in an array that doesn't contain 0?

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 "toSource". Try 2 in x. That will be false (since JavaScript arrays are 0-indexed).

See the MDN documentation.


The in operator doesn't do what you're thinking it does. The in operator returns true if the specified operand is a property of the object. For arrays, it returns true if the operand is a valid index (which makes sense if think of arrays as a special-case object where the properties are simply named 0, 1, 2, ...)

For example, try this:

javascript:var x=[1,4,6]; alert(2 in x);

It'll also return true, because "2" is a valid index into the array. In the same way, "0" is an index into the array, so also returns true.


Javascript's in operator does not check if a value is contained in an array. It checks if the object has a property or index. So var x = [4,5]; 4 in x; //false 1 in x; //true.

Because length is a property of x, "length" in x; //true