Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 415
Mariano Peterson Avatar asked Jun 18 '10 03:06

Mariano Peterson


People also ask

How does the in operator work in JavaScript?

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.

How to use in operator in JavaScript array?

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 .

Can you use the IN operator in an array?

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.

How do you check if a value exists in an array JavaScript?

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.


1 Answers

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.

like image 132
Matthew Flaschen Avatar answered Oct 11 '22 10:10

Matthew Flaschen