RangeError: Invalid array length
Error message
Invalid array length
Quick summary
You tried to create or resize an array with an invalid length — negative, non-integer, or too large.
Why this happens
Passed a negative number to the Array constructor
Passed a non-integer (float) as an array length
Set array.length to an invalid value
Minimal example
const arr = new Array(-1);const size = Math.max(0, Math.floor(-1));
const arr = new Array(size);Negative array lengths are invalid. Sanitize with Math.max(0, ...) to ensure a valid length.
How to diagnose
Check the value being passed to new Array() or assigned to .length
Ensure the value is a non-negative integer
Log the value to see if it is negative or a float
How to fix
Use Math.max(0, Math.floor(value)) to sanitize the length
Validate the input is a non-negative integer before using it
Use array literals [...] instead of new Array(n) when possible
How to prevent
Validate numeric inputs before using them as array lengths
Prefer array literals over the Array constructor