How to Fix RangeError: Invalid array length Error in JavaScript

RangeError: Invalid array length error typically occurs when “creating an Array or an ArrayBuffer of the array length either negative or greater than or equal to 232.” It can also occur if the length property is set manually to a value either negative or greater than or equal to 232.

Reproduce the error

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 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.

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