It's due to the fact that arrays in Javascript are just objects with some dedicated syntactic sugar.
Compare:
var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';
console.log(arr['0']);
console.log(arr[1]);
... to:
var obj = {};
obj[0] = 'foo';
obj['1'] = 'bar';
console.log(obj['0']);
console.log(obj[1]);
Basically, Array
is a type of Object
, with array specific methods and non-enumerable properties, such as length
, which can be instantiated with the dedicated shorthand syntax [ items... ]
The indices of an array are actually strings, just like all keys in any object, it works because referencing an object property using a number as a key will coerce that number into its string representation (in principle, that is. I assume most modern browsers have internally optimized this heavily).
Example:
var obj = {};
obj[1.5] = 'foo';
console.log('1.5' in obj);
console.log(obj[1.5]);
var arr = [];
arr[0.5] = 'foo';
console.log('0.5' in arr);
console.log(arr[0.5]);
arr[0] = 'bar';
arr[1] = 'baz';
console.log(arr.length);
console.log(Object.keys(arr));