A RangeError is thrown in JavaScript when a value is not within the set or range of allowed values for a particular operation. It is most commonly seen when creating arrays with invalid lengths or when calling a recursive function too deeply.
Why it happens
- •Passing a negative number or a non-integer to the Array constructor.
- •Exceeding the maximum call stack size with deeply recursive functions.
- •Calling toFixed(), toPrecision(), or toExponential() with out-of-range digits.
- •Setting String.prototype.repeat() with a negative or non-finite count.
Examples
Code that triggers the error
const items = new Array(-1);Error output
RangeError: Invalid array length
How to fix it
Validate the values you pass to built-in functions before calling them. For recursion, add a base case and verify the input reduces toward that base case. Use iterative solutions instead of recursive ones for very large inputs.
Fixed code
// Use a non-negative length
const items = new Array(5);
console.log(items.length); // 5
// Or initialize with values:
const filled = Array.from({ length: 5 }, (_, i) => i);
console.log(filled); // [0, 1, 2, 3, 4]Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free