JavaScript's index is 32 bit, so it seems that the array index should be able to go up to 4294967295 for a total of 4294967296 elements. But in fact the highest index is 4294967294. Since an array has a length
property, I don't see a reason for having a null as the last element. Is there a reason the maximum index is 4294967294 but not 4294967295?
This is because when you create an array using the Array
constructor you may supply it an optional length
as follows:
new Array(length);
The length
of an array is a 32-bit unsigned integer. Hence the length of the array may range from 0
to Math.pow(2, 32) - 1
which is 4294967295
.
For an array of length n
the indices range from 0
to n - 1
. Hence the maximum index of a JavaScript array is (Math.pow(2, 32) - 1) - 1
or Math.pow(2, 32) - 2
, which is 4294967294
.
Thus a JavaScript array may hold a maximum of 4294967295
elements and not 4294967296
elements.
I know. It's pretty illogical, but then again one element won't make a lot of difference.
The ECMA-262 specification (section 15.4) says:
A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 232-1.
The spec also says that the length
property of an array is always less than 232. That would seem to exclude 4294967295 as an array index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With