Sub topic 13
Recursion and Its Limits in JavaScript
This chapter assumes you know arrow functions, default parameters, rest/spread syntax, and reduce. It also assumes you have read the chapter on pure functions, because recursion works best on pure inputs and outputs. You need Node.js or a browser console to run the examples.
Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. Functional languages use it in place of loops, because a loop counter has to be reassigned and recursion keeps the state in parameters instead. JavaScript supports recursion well for small and tree-shaped data. It has one hard limit that languages like Haskell or Scheme do not share: the call stack.
The Two Parts of Every Recursive Function
Every recursive function needs these two parts:
- A base case: an input small enough to answer directly, with no further call.
- A recursive case: code that reduces the input and calls the function again, moving toward the base case.
Here is the array sum from the tutorial plan, with its base case written to be safe:
const sum = (xs) =>
xs.length === 0 ? 0 : xs[0] + sum(xs.slice(1));
console.log(sum([1, 2, 3, 4])); // 10
console.log(sum([])); // 0A popular shorter form destructures the array as [head, ...tail] and stops when head === undefined. That version stops early on arrays that contain undefined, such as [1, undefined, 5], and returns 1. Checking length tests whether the array is empty, which is the condition you actually mean.
What Happens on the Call Stack
Each call to sum creates a stack frame, a record holding that call's arguments and the point where it should resume. A frame stays on the stack until its call returns. sum([1, 2, 3]) cannot add anything until sum([]) answers, so all four frames exist at once.
Stack depth grows with input size. Engines cap the stack at a fixed amount of memory, which usually allows somewhere around 10,000 frames. The exact number depends on the engine, the flags it runs with, and how large each frame is.
Hitting the Limit
const countDown = (n) => (n === 0 ? 'done' : countDown(n - 1));
console.log(countDown(1000)); // done
try {
countDown(1e6);
} catch (e) {
console.log(e.name, '-', e.message);
// Node.js / Chrome: RangeError - Maximum call stack size exceeded
}Firefox reports the same failure as InternalError: too much recursion. Whatever the engine calls it, the error is not a logic bug in your function. The function is correct, and the runtime cannot hold that many pending calls.
Tail Calls and Why They Don't Save You
A tail call is a call that is the very last thing a function does, so that nothing is left to compute after it returns. countDown above makes a tail call. sum does not, because it still has to add xs[0] after the inner call returns.
You can rewrite sum into tail form with an accumulator, a parameter that carries the running result:
'use strict';
const sumAcc = (xs, i = 0, acc = 0) =>
i >= xs.length ? acc : sumAcc(xs, i + 1, acc + xs[i]);
console.log(sumAcc([1, 2, 3, 4])); // 10In languages with tail-call optimization (TCO), the runtime reuses the current frame for a tail call, so the stack stays flat. ES2015 requires proper tail calls in strict mode, but only Safari's JavaScriptCore ships them. V8 (Chrome, Node.js, Deno) and SpiderMonkey (Firefox) do not. On most runtimes, sumAcc overflows at the same depth as sum.
The accumulator form is still worth learning, because it is the first step toward the two workarounds below.
Hidden Cost: Copying on Every Call
xs.slice(1) and [head, ...tail] each build a new array on every call. For an array of n items, that copies about n²/2 elements in total, so the function runs in quadratic time. Passing an index, as sumAcc does, avoids the copies and leaves the input untouched, so the function stays pure.
| Version | Time | Extra memory | Stack-safe on large input |
|---|---|---|---|
| `[head, ...tail]` recursion | O(n²) | O(n²) copied over all calls | No |
| Index-based recursion | O(n) | O(n) frames | No |
| Trampolined recursion | O(n) | O(1) frames | Yes |
| `reduce` or a loop | O(n) | O(1) | Yes |
Workaround 1: Trampolining
A trampoline turns recursion into a loop. The recursive function returns a zero-argument function (a thunk) instead of making the call itself. A driver loop keeps calling thunks until it gets a value that is not a function.
const trampoline = (fn) => (...args) => {
let result = fn(...args);
while (typeof result === 'function') {
result = result();
}
return result;
};
const sumToStep = (n, acc = 0) =>
n === 0 ? acc : () => sumToStep(n - 1, acc + n);
const sumTo = trampoline(sumToStep);
console.log(sumTo(1e6)); // 500000500000Each thunk returns before the next one runs, so the stack never grows deeper than two frames. There are two costs. Every step allocates a closure, which makes the code slower than a loop. The function also cannot return a function as its final value, because the driver would call it.
Workaround 2: Iteration With an Explicit Stack
Recursion over trees is where the style is most natural. A tree's shape matches the shape of the code:
const tree = {
value: 1,
children: [
{ value: 2, children: [] },
{ value: 3, children: [{ value: 4, children: [] }] }
]
};
const sumTree = (node) =>
node.value + node.children.reduce((acc, child) => acc + sumTree(child), 0);
console.log(sumTree(tree)); // 10The stack depth here equals the tree's depth, not its node count. A balanced tree of a million nodes is only about 20 levels deep, so the recursive version is safe for it. Trees that are deep but narrow are the risk: deeply nested JSON, linked lists modelled as nested objects, or parse trees built from hostile input. For those, keep your own stack in an array:
const sumTreeIter = (root) => {
let total = 0;
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
total += node.value;
stack.push(...node.children);
}
return total;
};
console.log(sumTreeIter(tree)); // 10Heap memory is much larger than the call stack, so this version handles any depth. The mutation stays local to the function. Callers see the same input-to-output behavior they got from the recursive version, so sumTreeIter still counts as pure.
Choosing an Approach
- Use plain recursion for tree-shaped data with known, modest depth, and for code where clarity matters more than raw speed.
- Use
reduce,map, or a loop for flat lists of any size. Recursing over a flat list buys nothing in JavaScript. - Use a trampoline when the recursive form is the clearest way to state the logic and the depth is unbounded.
- Use an explicit stack for deep or untrusted trees, and in hot paths where trampoline allocations would show up in profiles.
Exercise
Write a recursive flatten that turns [1, [2, [3, [4]]], 5] into [1, 2, 3, 4, 5] without mutating its input. What determines the maximum stack depth it reaches?
Show answer
const flatten = (xs) => xs.reduce((acc, x) => (Array.isArray(x) ? [...acc, ...flatten(x)] : [...acc, x]), []); returns [1, 2, 3, 4, 5]. The stack depth equals the deepest level of nesting (4 here), not the total number of elements, so long flat arrays are safe and only deeply nested ones risk overflow. Using acc.concat(...) in place of the spreads gives the same result with less syntax.
Exercise
In Node.js, const len = (xs, i = 0) => (i >= xs.length ? i : len(xs, i + 1)); is in tail form and runs under 'use strict'. Will len(new Array(1e6).fill(0)) succeed? How would you make it succeed while keeping the recursive structure?
Show answer
It throws a RangeError, because V8 does not implement proper tail calls even in strict mode. To keep the recursive shape, return a thunk from the recursive case, () => len(xs, i + 1), and wrap the function with the trampoline helper. The wrapped call returns 1000000.