Should negative indexes in JavaScript arrays contribute to array length?
SO for me logically it seems like arr[-1] is also a part of arr.
Yes it is, but not in the way you think it is.
You can assign arbitrary properties to an array (just like any other Object in JavaScript), which is what you're doing when you "index" the array at -1
and assign a value. Since this is not a member of the array and just an arbitrary property, you should not expect length
to consider that property.
In other words, the following code does the same thing:
var arr = [1, 2, 3];
arr.cookies = 4;
alert(arr.length) // 3;
The length
property will return a number one higher than the highest assigned "index", where Array "indexes" are integers greater than or equal to zero. Note that JS allows "sparse" arrays:
var someArray = [];
someArray[10] = "whatever";
console.log(someArray.length); // "11"
Of course if there are no elements then length
is 0
. Note also that the length
doesn't get updated if you use delete
to remove the highest element.
But arrays are objects, so you can assign properties with other arbitrary property names including negative numbers or fractions:
someArray[-1] = "A property";
someArray[3.1415] = "Vaguely Pi";
someArray["test"] = "Whatever";
Note that behind the scenes JS converts the property names to strings even when you supply a number like -1
. (The positive integer indexes also become strings, for that matter.)
Array methods, like .pop()
, .slice()
, etc., only work on the zero-or-higher integer "indexes", not on other properties, so length
is consistent on that point.