How to Fix a RangeError in JavaScript
A JavaScript RangeError means an operation received a value outside its allowed range. Trace the failing call, check its input, and apply the rule for that operation.
A JavaScript RangeError means an operation received a value outside the range it allows. There is no single fix: read the exact error message and stack trace, find the call that failed, inspect the value passed to it, then validate or correct that value using the operation’s rules. Avoid changing a limit or swallowing the exception before you know what value is invalid.
1. Find the operation that threw
- Read the full error name and message. Messages such as
invalid array length,precision is out of range, andradix must be an integerpoint to different APIs. - Use the stack trace to locate the first frame in your code. Inspect the arguments at that call, including values produced by parsing, arithmetic, or user input.
- Check whether the value has the expected type and whether it is finite. A numeric string,
NaN, a fraction, or a negative result can violate an API’s range even if the original input looked reasonable. - Apply the documented constraint for that operation. Reproduce the failing input and a valid boundary input, then keep a regression case for the failure if appropriate.
try {
const result = operationThatMayThrow(value);
console.log(result);
} catch (error) {
if (error instanceof RangeError) {
console.error(error.name, error.message);
console.error(error.stack);
}
throw error; // Preserve the failure while debugging.
}
Replace operationThatMayThrow with the actual call from the stack. Logging the value immediately before that call is often more useful than logging it only in a distant caller. Catching an error is useful for diagnostics or a deliberate recovery path; catching and ignoring it leaves the invalid input and failed operation unresolved.
2. Fix common RangeError messages
RangeError: invalid array length
Look for new Array(value), assignments to array.length, buffer allocation, and code such as push or concat that can grow an array. Array length must be a supported non-negative integer; MDN documents the maximum Array length as 232−1. ArrayBuffer limits vary by platform and engine, so do not assume the Array limit is a portable buffer-allocation limit. See MDN’s invalid array length reference.
// Wrong if you intend one element whose value is count:
const items = new Array(count);
// One-element array:
const oneItem = [count];
// If count is a requested size, validate before allocating:
function allocateArray(size, maxSize) {
if (!Number.isInteger(size) || size < 0 || size > maxSize) {
throw new RangeError(`size must be an integer from 0 to ${maxSize}`);
}
return new Array(size);
}
Choose maxSize from the application’s actual memory and product limits, not just the language maximum. A technically representable allocation can still exhaust available memory. Validate array length assignments and calculations that can overflow into an invalid or unexpectedly large size as well.
RangeError: precision is out of range
Check the argument to toFixed, toExponential, or toPrecision. toFixed and toExponential accept digits from 0 through 100 inclusive; toPrecision accepts 1 through 100 inclusive. See MDN’s precision range reference.
function fixed(value, digits) {
if (!Number.isInteger(digits) || digits < 0 || digits > 100) {
throw new RangeError("digits must be an integer from 0 to 100");
}
return value.toFixed(digits);
}
function significant(value, precision) {
if (!Number.isInteger(precision) || precision < 1 || precision > 100) {
throw new RangeError("precision must be an integer from 1 to 100");
}
return value.toPrecision(precision);
}
If precision comes from a form or query parameter, decide what invalid input means: reject it with a clear validation message, or intentionally clamp it to a product-defined range. Do not silently clamp unless that is the behavior users should expect.
RangeError: radix must be an integer
The optional radix to Number.prototype.toString() or BigInt.prototype.toString() must be an integer from 2 through 36. See MDN’s bad radix reference.
function formatInRadix(value, radix) {
if (!Number.isInteger(radix) || radix < 2 || radix > 36) {
throw new RangeError("radix must be an integer from 2 to 36");
}
return value.toString(radix);
}
console.log(formatInRadix(255, 16)); // "ff"
Use base 10 explicitly only when you need ordinary decimal string conversion; calling toString() without a radix already uses its default representation. A computed radix such as 2.5 or an unsupported base must be rejected or mapped deliberately.
Maximum call stack size exceeded or too much recursion
These messages can represent stack exhaustion: Chrome and Safari may report a RangeError, while Firefox reports InternalError: too much recursion. Look for repeated frames and recursion that lacks a terminating base case or fails to make progress. Check MDN’s recursion error reference.
// Recursive version: each call must move toward the base case.
function sumTo(n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("n must be a non-negative integer");
}
if (n === 0) return 0;
return n + sumTo(n - 1);
}
// Iterative version avoids growing the call stack for large inputs.
function sumToIterative(n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("n must be a non-negative integer");
}
let total = 0;
for (let current = n; current > 0; current--) total += current;
return total;
}
Do not rely on a numeric recursion-depth threshold copied from another runtime; the practical limit is not portable. For deeply nested or untrusted input, consider an iterative traversal and impose an application-appropriate depth or size bound.
3. Validate values at the boundary
When a value comes from an HTTP request, configuration file, database, or UI, validate it before passing it to a range-sensitive API. Convert deliberately, then verify the result: Number.isInteger checks whole numbers, and Number.isFinite rejects NaN and infinities. A reusable validator can make the contract explicit:
function requireIntegerInRange(value, min, max, name) {
if (!Number.isInteger(value) || value < min || value > max) {
throw new RangeError(`${name} must be an integer from ${min} to ${max}`);
}
return value;
}
const digits = requireIntegerInRange(Number(input.digits), 0, 100, "digits");
const output = Number(amount).toFixed(digits);
For inputs where decimal strings, empty values, or whitespace have special meaning, validate the raw input format too. Conversion alone can produce surprising values. Keep the chosen minimum, maximum, and recovery behavior next to the API call so future changes do not obscure the contract.
4. Troubleshooting checklist
| Symptom | Likely cause | What to check or change |
|---|---|---|
invalid array length |
Negative, fractional, or unsupported array size; a mistaken constructor argument | Inspect allocation and length writes; use [value] for one element; validate and bound sizes. |
| Precision out of range | Digits or precision argument outside the method’s bounds | Check integer-ness and the method-specific range before formatting. |
| Radix must be an integer | Radix is fractional, below 2, or above 36 | Validate the radix as an integer from 2 to 36. |
| Maximum call stack / too much recursion | Missing base case, no progress, or input nesting too deep | Trace repeated frames; fix termination, use iteration, or bound input depth. |
| Error appears only for some records | Data-dependent calculation or conversion produced an invalid value | Log the input and derived argument at the failing call; test the smallest failing record. |
| Error differs between browsers | Runtime-specific wording or limits | Use the operation and stack frame as the diagnosis; do not key application logic to message text. |
5. Reliability, performance, and cost
Validation adds a small check at the boundary and can prevent invalid allocations, formatting calls, or recursive work from reaching the failing operation. Put validation where untrusted or variable data enters the relevant code path rather than scattering duplicate checks everywhere. For bulk processing, decide whether one invalid record should reject the whole batch or be reported and skipped; make that policy explicit and preserve enough context to identify the record.
Do not raise limits as a reflex. Very large arrays and buffers consume memory, while unbounded recursion consumes call stack. A safe application-level maximum should reflect the actual task and resources. Catching errors can support graceful reporting, but it does not make a bad value valid. The most reliable fix is one that rejects, corrects, or safely handles the invalid input before the operation.
6. Or skip the browser setup
This JavaScript error is fixed in the operation that throws it; a screenshot service will not repair application code. If you need to capture a page showing the error, or document the corrected result, ScreenshotNeo provides a website screenshot API and MCP server. Its API call is independent of the RangeError diagnosis.
For the do-it-yourself route, validate the operation’s input as shown above and reproduce the failing case. For a rendered-page screenshot, one GET request can return an image or PDF. See the ScreenshotNeo API documentation.
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));
ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server gives AI agents tools named take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. Create a free account and get 1,000 screenshots a month with no card.
7. FAQ
Is a RangeError always caused by a number?
No. The offending value may be an array size, formatting argument, radix, or recursion path. The message and stack trace identify which operation’s constraint matters.
Should I catch every RangeError?
No. Catch one when your code can report a useful validation error or recover safely. Do not hide it and continue as if the operation succeeded.
Are RangeError messages standardized across browsers?
The error category is useful, but wording and some runtime limits can differ. Diagnose by the failed API and stack location, not by matching a message string.
Where can I find other RangeError cases?
MDN’s JavaScript error reference lists additional messages. Apply the documented constraint for the specific operation in your trace.


