Note that when you use a position (or 0) index, values are placed within the array:
var array = [];
array[0] = "Foo";
array[1] = "Bar";
// Result: ["Foo", "Bar"]
// Length: 2
This is not the case when you add non-index values (not 0-9+):
var array = [];
array[0] = "Foo";
array[1] = "Bar";
array[-1] = "Fizzbuzz"; // Not a proper array index - kill it
// Result: ["Foo", "Bar"]
// Length: 2
Values are only placed in the array when you play by the rules. When you don't, they aren't accepted. They are however accepted on the Array object itself, which is the case with just about anything in JavaScript. Even though ["Foo", "Bar"]
are the only values in our array, we can still access "Fizzbuzz"
:
array[-1]; // "Fizzbuzz"
But note again that this isn't part of the array values, since its "index" isn't valid. It was instead added onto the array as just another member. We could access other array members in the same fashion:
array["pop"]; // function pop() { [native code] }
Note here that we're accessing the pop
method on the array, which informs us that this contains native code. We're not accessing any of the array values with a key of "pop", but rather a member on the array object itself. We can further confirm this by cycling over the public members of the object:
for (var prop in array)
console.log(prop, array[prop]);
Which spits out the following:
0 Foo
1 Bar
-1 Fizzbuzz
So again, it's on the object, but it's not in the array.
Awesome question! Caused me to do a double-take for sure.