Imagine an object and an array that looks like this:
var obj = { foo: "bar" };
var arr = ["bar"];
You would access the obj
's bar
value by invoking the corresponding key on that object, i.e.
obj.foo // "bar"
An alternative way of doing this would be to use the array syntax:
obj["foo"] // "bar"
As you can see, each of the object's keys has a name (i.e. foo). An array is still an object, only that it's 'keys' (or indexes) are incremental numeric values. Thusly, we access the various elements in the array using their respective indexes in that array, i.e:
arr[0] // "bar"
In this way, use of the in
keyword should become clearer. MDN defines the in
keyword as the following:
The in operator returns true if the specified property is in the specified object.
So, in keeping with our previous example, consider the following:
"foo" in obj // true
"bar" in obj // false
The above happens because, as you already know, the variable obj
only has one element in it, and that element's key is foo
, and it's value is bar. With this in mind, consider your array:
var ar = [];
var a = 4;
ar.push(a);
0 in ar // true
4 in ar // false
As you can now hopefully see, in much the same way it investigates the js object, for arrays the in
keyword is still looking for the key and not for the value corresponding to that key. Though the value at index 0 is 4, it's key (or index) is still 0. Hence, it should be clear why calling
4 in ar // false
Returns false
- there's nothing in that array's fourth index. Hope this helps.