Skip to content

RangeError: flat depth too large

Quick summary

You passed a huge depth (or Infinity) to .flat — the recursive flattening runs out of stack space.

Why this happens

  • Passing Infinity as the depth to .flat

  • Deeply nested arrays combined with a large depth argument

  • Calculating depth from untrusted input without a cap

Minimal example

✗ Broken code
let arr = [1];
for (let i = 0; i < 100000; i++) arr = [arr];
const flat = arr.flat(Infinity); // RangeError / stack overflow
✓ Fixed code
let arr = [1];
for (let i = 0; i < 100000; i++) arr = [arr];
function deepFlat(a) {
  while (a.some(x => Array.isArray(x))) a = [].concat(...a);
  return a;
}
const flat = deepFlat(arr); // [1] — iterative, no stack overflow

flat(Infinity) recurses for each nesting level, so a 100000-deep array overflows the stack. An iterative flattener avoids recursion entirely.

How to diagnose

  • Read the RangeError or 'Maximum call stack size exceeded'

  • Log the depth value and the nesting level of the array

  • Check whether Infinity was passed accidentally

How to fix

  • Use a small fixed depth (e.g., 1 or 2) or omit it for a single level

  • Use Infinity only when you are sure the array is not pathologically deep

  • Implement an iterative flattener for unbounded depth

How to prevent

  • Cap the depth at a reasonable maximum for your data

  • Validate array nesting before calling .flat with large depths

Related Resources

Related Glossary

Related Lessons

← Back to language