RangeError — Stack Overflow & Invalid Values
TL;DR
RangeError is thrown when a value is outside its allowed range — most commonly from infinite recursion (stack overflow) or invalid array/string sizes.
Explanation
RangeError: Maximum call stack size exceeded is the most common form — infinite or too-deep recursion. Other causes: new Array(-1) (negative size), toFixed(200) (precision out of range), String.fromCodePoint(Infinity). Unlike ReferenceError (undeclared variable) or TypeError (wrong type), RangeError is about a value being outside its valid numeric or structural range. Catching: try/catch catches RangeError from bad API calls but NOT stack overflow from recursion in most engines — stack overflow crashes the current execution context. Detection: check for recursion with a depth counter, use iterative algorithms for large inputs.
Common Misconception
✗ try/catch always catches stack overflow RangeError — stack overflow from deep recursion often crashes the JS engine context before catch can run. Guard with depth counters instead.
Why It Matters
RangeError from stack overflow is the most common crash in recursive algorithms on user-supplied data — depth-limiting is essential for production code.
Common Mistakes
- Recursive functions without a base case or depth limit.
- Calling toFixed() with user-supplied precision — can be > 100 (throws RangeError).
- Not knowing new Array(n) throws for negative n.
Code Examples
✗ Vulnerable
function flatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []
);
}
flatten(deeplyNestedArray); // RangeError: Maximum call stack size exceeded
✓ Fixed
// Iterative with explicit stack:
function flatten(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) stack.push(...item);
else result.push(item);
}
return result.reverse();
}
// Or with depth limit:
function flatten(arr, depth = 10) {
if (depth === 0) return arr;
return arr.flat(depth);
}
References
Tags
Edited
5 Apr 2026
Views
50
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 6
Perplexity 6
Unknown AI 3
Google 2
Meta AI 2
ChatGPT 1
Majestic 1
Ahrefs 1
Also referenced
How they use it
crawler 21
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟠 High
⚙ Fix effort: Medium
⚡ Quick Fix
Add depth counters to recursive functions. Use iterative algorithms with explicit stacks for large inputs. Validate numeric args before passing to toFixed/Array constructor.
📦 Applies To
javascript ES5
web
cli
🔗 Prerequisites
🔍 Detection Hints
function.*\(.*\).*{[^}]*\(
Auto-detectable:
✗ No
eslint
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✗ Manual fix
Fix: High
Context: Function
Tests: Update
CWE-674
CWE-400