Sub topic 13
Recursion and Its Limits in JavaScript
This chapter assumes you know arrow functions, rest and spread syntax, array destructuring, and what a pure function is. Recursion is how functional code repeats work without loops and mutable counters. In JavaScript you also need to know where it breaks.
The Working Model
A recursive function calls itself on a smaller piece of the problem. It needs two parts:
- Base case: an input simple enough to answer directly. Without one, the function never stops.
- Recursive case: the function reduces the input and calls itself, moving toward the base case.
const sum = ([head, ...tail]) =>
head === undefined ? 0 : head + sum(tail);
console.log(sum([1, 2, 3, 4])); // 10The function never reassigns a variable. Each call gets its own head and tail, so it stays pure.
Every call adds a stack frame. A stack frame is the engine's record of a call's arguments and where to return. The frames stay open until the base case returns, and then they resolve in reverse order.
Where Recursion Fits Well
Recursion works best when the data itself is recursive, such as trees, nested menus, file systems, or JSON. On that kind of data the code follows the shape of the data:
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)); // 10Tree depth is usually small, so the stack is not a concern here.
The Limits
Stack overflow
Engines cap the call stack. In V8, which runs Node.js and Chrome, the cap is roughly ten thousand frames by default. The exact number depends on frame size.
const depth = (n) => (n === 0 ? 0 : 1 + depth(n - 1));
try {
depth(1e6);
} catch (e) {
console.log(e instanceof RangeError, e.message);
// true Maximum call stack size exceeded
}No tail-call optimization
ES2015 specifies proper tail calls. With them, a call in tail position would reuse the current frame instead of adding a new one. Only Safari's JavaScriptCore ships this feature, and only in strict mode. Node.js, Chrome, and Firefox do not. Rewriting a function into tail-recursive form therefore does not make it safe in most environments.
Hidden costs
[head, ...tail] copies the rest of the array on every call, so sum runs in O(n²) time. It also stops early at the first undefined element.
Converting to Iteration
When depth is unbounded, replace the call stack with an explicit array that you manage yourself:
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)); // 10This function mutates local variables, but no caller can see that mutation. The same input always gives the same output, so the function is still pure from the outside.
Exercise
Why does sum([1, undefined, 3]) return 1 instead of throwing or returning NaN?
Show answer
The base case checks head === undefined. When head is the undefined element, the function treats it as the end of the array and returns 0, so the result is 1 + 0. A check such as xs.length === 0 avoids this bug.
Exercise
Write a recursive countDown(n) that returns an array [n, n-1, ..., 1], and state the input that makes it fail in Node.js.
Show answer
const countDown = (n) => (n <= 0 ? [] : [n, ...countDown(n - 1)]); It throws a RangeError for inputs around 10,000 or more, because each call adds a stack frame. It also copies arrays on every call, so a loop or Array.from({ length: n }, (_, i) => n - i) is better for large n.