How to Fix RangeError: Invalid array length in JavaScript

To fix the RangeError: Invalid array length in JavaScript, ensure that you only create arrays with valid lengths. For instance, you can use Math.max() to make sure the length is at least 0.

JavaScript raises the RangeError: Invalid array length error when creating an array with an invalid length, such as a negative number or a non-integer value. The arrays in JavaScript cannot have negative lengths or non-integer lengths.

let listA = new Array(4294967296)
let listB = new Array(-100)

console.log(listA.length)
console.log(listB.length)

Output

RangeError: Invalid array length 

You can see that we got a RangeError when you try to create an array whose length is invalid.

How to fix the RangeError

To fix this error, you should only create arrays with valid lengths. For instance, you can use the Math.max() function to ensure the length is at least 0.

const desiredLength = -5;
const validLength = Math.max(desiredLength, 0);

const arr = new Array(validLength);
console.log(arr)

Output

[]

If you are calculating the length based on some other variables, ensure to validate your calculations before creating the array. This will prevent the error from being thrown.

Leave a Comment