Why is a JavaScript Array index at most 4294967294 but not 4294967295?
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.
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.