JS: Array max number of elements

By Xah Lee. Date: . Last updated: .

Max number of elements

The max number of elements is 2**32 - 1 (which is 4 294 967 295).

Max index is therefore 2**32 - 2 (which is 4 294 967 294). One smaller than max number of elements. Because index start at 0.

When property name is integer-like in that range, it is treated as array index, else it's a property key.

Note: if you create a array with just 1,000,000 items, the browser will become not responsive.

// When array index is beyond 2^32 - 2, it is treated as a property key.

// this is max index
console.assert(2 ** 32 - 2 === 4294967294);

// array
const xx = [];
// add a index with value to array
xx[2 ** 32 - 2] = "a";
console.log(xx);
// [ <4294967294 empty items>, "a" ]

// now do the same but with index beyond max length
const yy = [];
yy[2 ** 32 - 1] = "a";
console.log(yy);
// [ "4294967295": "a" ]
// note it is printed differently

// is still a true array
console.assert(Array.isArray(yy));