Skip to content
jshacks.dev
Fundamentals

JavaScript RangeError Explained With Causes and Fixes

JavaScript throws RangeError when a value has the right type but is out of range. See array length, repeat, toFixed, stack overflow and bad dates with fixes.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js and Vite logos.

A RangeError means the value you passed is the right kind of thing and the wrong size: a negative array length, a string repeated an infinite number of times, a number with 200 decimal places, a function that called itself until the stack ran out. It is a smaller family than TypeError, with a handful of causes that account for nearly every case in real code. Learning them takes ten minutes and saves hours, because the message always names the limit that was crossed. This post lists the common causes with the message Node.js 24 prints, explains how the stack overflow case differs from the others, shows how to prevent each one and how to catch it, and ends with how to throw your own. The messages come from V8, which runs Node.js, Chrome and Edge, so other engines word them differently, and code should match on the error type and not on the text.

What the error means

The specification throws RangeError when a value is a valid type but not in the set of allowed values for the operation. Here are the usual suspects in one run.

JavaScript
const cases = [
  () => new Array(-1),
  () => "ab".repeat(-1),
  () => (1.5).toFixed(101),
  () => (10).toString(1),
  () => new Date(NaN).toISOString(),
  () => String.fromCodePoint(-1),
  () => BigInt(1.5),
  () => 1.5.toPrecision(0),
];

for (const run of cases) {
  try {
    run();
  } catch (e) {
    console.log(e.name, "|", e.message);
  }
}
Text
RangeError | Invalid array length
RangeError | Invalid count value: -1
RangeError | toFixed() digits argument must be between 0 and 100
RangeError | toString() radix must be between 2 and 36
RangeError | Invalid time value
RangeError | Invalid code point -1
RangeError | The number 1.5 cannot be converted to a BigInt because it is not an integer
RangeError | toPrecision() argument must be between 1 and 100

The messages state the allowed range when there is one. The type of the argument was fine each time: the problem was the number itself. This separates it from a TypeError, where the value could not be used at all, and from a SyntaxError, where the text could not be parsed.

Invalid array length

An array length must be an integer from 0 to 4,294,967,295, and anything else is a RangeError.

JavaScript
const attempts = [
  () => new Array(-1),
  () => new Array(1.5),
  () => new Array(2 ** 32),
  () => { const list = []; list.length = -5; },
  () => new Array("3"),
];

for (const run of attempts) {
  try {
    const result = run();
    console.log("ok", result);
  } catch (e) {
    console.log(e.name, "-", e.message);
  }
}
Text
RangeError - Invalid array length
RangeError - Invalid array length
RangeError - Invalid array length
RangeError - Invalid array length
ok [ '3' ]

The last case is not an error and is a classic trap: new Array("3") with a string argument is an array containing the string, while new Array(3) is an empty array of length 3. The length comes from user input, a database field or a calculation that went negative, and the fix is to validate it before creating the array: Number.isInteger(n) && n >= 0. Prefer Array.from({ length: n }, fn), which fails the same way for a bad n and avoids the single-number constructor entirely.

repeat, padStart and string size

JavaScript
const tests = [
  () => "ab".repeat(-1),
  () => "ab".repeat(Infinity),
  () => "ab".repeat(2 ** 30),
  () => "ab".padStart(2 ** 30, "x"),
];

for (const run of tests) {
  try {
    run();
    console.log("ok");
  } catch (e) {
    console.log(e.name, "-", e.message);
  }
}
Text
RangeError - Invalid count value: -1
RangeError - Invalid count value: Infinity
RangeError - Invalid string length
RangeError - Invalid string length

A negative or infinite count is rejected by repeat(). A count that would make a string longer than the engine's maximum is rejected with Invalid string length, and V8's limit is a little under 2^29 characters, about half a billion. The exact figure differs between engines and versions, so never write code that depends on it. The usual source of this error is a loop that builds a string without a bound, or a repeat count taken from untrusted input. Cap the count at a number that makes sense for your use before calling.

Number formatting limits

toFixed(), toPrecision() and toString(radix) have fixed ranges.

JavaScript
const n = 1234.5678;

console.log(n.toFixed(2));
console.log(n.toPrecision(6));
console.log((255).toString(16), (255).toString(2));

for (const run of [() => n.toFixed(101), () => n.toPrecision(0), () => (5).toString(37)]) {
  try {
    run();
  } catch (e) {
    console.log(e.message);
  }
}
Text
1234.57
1234.57
ff 11111111
toFixed() digits argument must be between 0 and 100
toPrecision() argument must be between 1 and 100
toString() radix must be between 2 and 36

The limits are 0 to 100 digits for toFixed(), 1 to 100 for toPrecision() and 2 to 36 for the radix. A digits argument that comes from a settings object or a function parameter needs a clamp: Math.min(Math.max(digits, 0), 100). For display, Intl.NumberFormat with maximumFractionDigits has its own range and throws a RangeError outside it, as the Intl.NumberFormat post shows.

Invalid dates

Date does not throw for a bad date until you ask it to describe itself.

JavaScript
const bad = new Date("not a date");

console.log(bad.getTime());
console.log(String(bad));
console.log(Number.isNaN(bad.getTime()));

try {
  bad.toISOString();
} catch (e) {
  console.log(e.name, "-", e.message);
}

console.log(JSON.stringify({ when: bad }));
Text
NaN
Invalid Date
true
RangeError - Invalid time value
{"when":null}

The invalid date is a valid object whose time value is NaN. Reading it gives NaN or the text Invalid Date, and toISOString() throws a RangeError, while JSON.stringify() turns it into null, because toJSON() returns null for an invalid date. This difference is how a bad date gets silently stored as null in one place and crashes a report in another. Check validity at the point you create the date: Number.isNaN(date.getTime()).

Maximum call stack size exceeded

This is the one that surprises people, since it is a RangeError and has nothing to do with a number being too big.

JavaScript
function recurse(depth) {
  return recurse(depth + 1) + 1;
}

try {
  recurse(0);
} catch (e) {
  console.log(e instanceof RangeError);
  console.log(e.name, "-", e.message);
}
Text
true
RangeError - Maximum call stack size exceeded

Each call uses a frame of memory on the call stack, and the stack has a fixed size. A function that calls itself with no end, or with an end that is too deep, runs out of frames. The depth that fits depends on the engine, the frame size and the platform, so we do not give a number: it varies from thousands to tens of thousands of calls. The bug is almost always a missing or wrong base case, as above. When the recursion is legitimate but deep, such as walking a very long linked list, rewrite it as a loop with an explicit stack.

JavaScript
function sumTo(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
}

console.log(sumTo(1_000_000));

function flatten(tree) {
  const out = [];
  const stack = [tree];
  while (stack.length > 0) {
    const node = stack.pop();
    if (Array.isArray(node)) {
      for (let i = node.length - 1; i >= 0; i--) stack.push(node[i]);
    } else {
      out.push(node);
    }
  }
  return out;
}

console.log(flatten([1, [2, [3, [4]]], 5]));
Text
500000500000
[ 1, 2, 3, 4, 5 ]

The loop version handles a million steps with no growth of the stack. The flatten function replaces recursion with an array used as a stack, which lives on the heap and can grow far larger. Catching the stack overflow and continuing is a last resort, since a handler that runs on a nearly full stack can itself overflow, and the state of the interrupted work is unknown.

Typed arrays and buffers

JavaScript
const attempts = [
  () => new ArrayBuffer(-1),
  () => new Uint8Array(-1),
  () => new Uint8Array(new ArrayBuffer(4), 5),
  () => new Uint16Array(new ArrayBuffer(3)),
];

for (const run of attempts) {
  try {
    run();
  } catch (e) {
    console.log(e.name);
  }
}
Text
RangeError
RangeError
RangeError
RangeError

A negative size, an offset past the end of the buffer, and a byte length that is not a multiple of the element size, here three bytes for a type of two bytes, are all RangeError. Binary parsing code that reads lengths from a file header should validate them against the buffer before creating views, since a corrupted or hostile length would otherwise reach these constructors.

Throwing your own

JavaScript
function percent(value) {
  if (typeof value !== "number") {
    throw new TypeError(`percent: expected a number, got ${typeof value}`);
  }
  if (value < 0 || value > 100) {
    throw new RangeError(`percent: ${value} is outside 0 to 100`);
  }
  return `${value}%`;
}

for (const input of [50, 150, "50"]) {
  try {
    console.log(percent(input));
  } catch (e) {
    console.log(e.name, "-", e.message);
  }
}
Text
50%
RangeError - percent: 150 is outside 0 to 100
TypeError - percent: expected a number, got string

The convention is to check the type first and throw TypeError, then check the range and throw RangeError. A caller can then tell the two mistakes apart without reading the message, and a test can assert on the class.

A mistake we hit: user input as a size

JavaScript
function makeGrid(rows, cols) {
  return Array.from({ length: rows }, () => new Array(cols).fill(0));
}

console.log(makeGrid(2, 3));

for (const [rows, cols] of [[2, -1], [2, "3"], [-1, 3], [2, 1e10]]) {
  try {
    makeGrid(rows, cols);
    console.log(rows, cols, "ok");
  } catch (e) {
    console.log(rows, cols, e.name);
  }
}
Text
[ [ 0, 0, 0 ], [ 0, 0, 0 ] ]
2 -1 RangeError
2 3 ok
-1 3 ok
2 10000000000 RangeError

Two results deserve a second look. The row count -1 did not throw: Array.from({ length: -1 }) treats a negative length as zero and returns an empty array, so a bad value passed silently. The string "3" for columns produced a one-element array containing the string, and fill(0) filled it, so the grid has the wrong shape with no error. We now validate sizes with Number.isInteger(n) && n >= 0 && n <= MAX at every boundary where a number comes from outside, and the RangeError is thrown by us, with a message that names the parameter.

Choosing between the fixes

The message saysThe usual fix
Invalid array lengthValidate the length is an integer from 0 up
Invalid count valueCheck the count is finite and not negative
Invalid string lengthBound the loop or the repeat count
toFixed() digits argumentClamp the digits to the allowed range
Invalid time valueCheck getTime() is not NaN before formatting
Maximum call stack size exceededFix the base case, or use a loop with an explicit stack

Practical rules we follow

Validate numbers that come from outside before they become sizes, counts or digits. Clamp when a value can be adjusted and reject when it cannot. Treat a stack overflow as a design signal and not a condition to catch. Throw RangeError from your own code for values of the right type that are out of bounds, and TypeError for the wrong type. Never match on the message text. And log the offending value with the error, because the message says what the limit was and not what you passed.

Where RangeError stops being the right diagnosis

It says a limit was crossed and not why the value was bad. The bad value usually comes from a calculation that went negative, a missing default or untrusted input. Some range problems do not throw: a negative Array.from length is treated as zero, and parseInt of garbage is NaN. And some out-of-range operations throw other errors, such as decodeURIComponent throwing a URIError. The reference is in the MDN RangeError page and the ECMAScript specification.

Taggederrors
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.