You’re reading the English version of this content since no translation exists yet for this locale. Help us translate this article!
RangeError: Array length must be a finite positive integer (Edge) RangeError: invalid array length (Firefox) RangeError: Invalid array length (Chrome) RangeError: Invalid array buffer length (Chrome)
What went wrong?
An invalid array length might appear in these situations:
- When creating an
ArrayBufferwhich has a length which is either negative or larger or equal to 232, or
- when setting the
Array.lengthproperty to a value which is either negative or larger or equal to 232.
ArrayBuffer length limited? The
length property of an
Array or an
ArrayBuffer is represented with an unsigned 32-bit integer, that can only store values which are in the range from 0 to 232-1.
If you are creating an
Array, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the
Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor.
new Array(Math.pow(2, 40)) new Array(-1) new ArrayBuffer(Math.pow(2, 32)) new ArrayBuffer(-1) let a = ; a.length = a.length - 1; // set -1 to the length property let b = new Array(Math.pow(2, 32) - 1); b.length = b.length + 1; // set 2^32 to the length property
[ Math.pow(2, 40) ] // [ 1099511627776 ] [ -1 ] // [ -1 ] new ArrayBuffer(Math.pow(2, 32) - 1) new ArrayBuffer(0) let a = ; a.length = Math.max(0, a.length - 1); let b = new Array(Math.pow(2, 32) - 1); b.length = Math.min(0xffffffff, b.length + 1); // 0xffffffff is the hexadecimal notation for 2^32 - 1 // which can also be written as (-1 >>> 0)