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;

Leave a Comment