Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Replace deep recursion with a stack in JavaScript

150 deep recursion, replaced by an explicit stack

hard

Sum the integers to 200,000 recursively and watch it blow the call stack, then write it in tail position and watch that blow up too. Fix it with a loop. Then build a 50,000-deep tree, walk it recursively (it throws) and with an explicit stack array (it does not), showing that the stack version produces the same pre-order and that the push order is what decides sibling order. Finish with a trampoline for mutual recursion that no rewrite can flatten.

Stuck? Three hints, smallest first
  1. 1. Catch the failure rather than avoiding it: try { deep(); } catch (e) { e.constructor.name }.
  2. 2. ES6 specified proper tail calls and essentially no engine shipped them, so a tail-recursive form still consumes one frame per call.
  3. 3. An explicit stack is an array you push children onto and pop from. pop is last-in-first-out, so push children in REVERSE to keep left-to-right pre-order.

The answer

const DEPTH = 200000;

const sumRecursive = (n) => (n === 0 ? 0 : n + sumRecursive(n - 1));
const sumTail = (n, acc = 0) => (n === 0 ? acc : sumTail(n - 1, acc + n));
const sumLoop = (n) => { let total = 0; for (let i = n; i > 0; i--) total += i; return total; };

let recursiveFailure, tailFailure;
try { sumRecursive(DEPTH); recursiveFailure = 'no throw'; } catch (e) { recursiveFailure = e.constructor.name; }
try { sumTail(DEPTH); tailFailure = 'no throw'; } catch (e) { tailFailure = e.constructor.name; }
const shallowStillFine = [sumRecursive(100), sumTail(100), sumLoop(100)];

const chainOf = (depth) => {
  let node = { id: depth, kids: [] };
  for (let i = depth - 1; i >= 1; i--) node = { id: i, kids: [node] };
  return node;
};

const small = {
  id: 1,
  kids: [{ id: 2, kids: [{ id: 4, kids: [] }, { id: 5, kids: [] }] }, { id: 3, kids: [] }],
};

const walkRecursive = (node, out) => {
  out.push(node.id);
  for (const kid of node.kids) walkRecursive(kid, out);
  return out;
};

const walkStack = (root) => {
  const out = [];
  const stack = [root];
  let highWater = 0;
  while (stack.length > 0) {
    if (stack.length > highWater) highWater = stack.length;
    const node = stack.pop();
    out.push(node.id);
    for (let i = node.kids.length - 1; i >= 0; i--) stack.push(node.kids[i]);
  }
  return { out, highWater };
};

const walkStackForwardPush = (root) => {
  const out = [];
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    out.push(node.id);
    for (const kid of node.kids) stack.push(kid);
  }
  return out;
};

const smallRecursive = walkRecursive(small, []);
const smallStack = walkStack(small).out;
const smallForwardPush = walkStackForwardPush(small);

const deep = chainOf(50000);
let deepRecursive;
try { deepRecursive = walkRecursive(deep, []).length; } catch (e) { deepRecursive = e.constructor.name; }
const deepStack = walkStack(deep);
const deepStackFacts = [deepStack.out.length, deepStack.out[0], deepStack.out[49999], deepStack.highWater];

const trampoline = (fn) => (...args) => {
  let out = fn(...args);
  while (typeof out === 'function') out = out();
  return out;
};
const isEvenStep = (n) => (n === 0 ? true : () => isOddStep(n - 1));
const isOddStep = (n) => (n === 0 ? false : () => isEvenStep(n - 1));
const isEvenSafely = trampoline(isEvenStep);

function isEvenDirect(n) { return n === 0 ? true : isOddDirect(n - 1); }
function isOddDirect(n) { return n === 0 ? false : isEvenDirect(n - 1); }
let mutualFailure;
try { isEvenDirect(100000); mutualFailure = 'no throw'; } catch (e) { mutualFailure = e.constructor.name; }

console.log('recursive :', recursiveFailure, '| tail form:', tailFailure, '| shallow:', shallowStillFine);
console.log('loop      :', sumLoop(DEPTH));
console.log('small tree:', smallRecursive, smallStack, smallForwardPush);
console.log('deep tree :', deepRecursive, '->', deepStackFacts);
console.log('trampoline:', isEvenSafely(100000), isEvenSafely(99999), '| direct:', mutualFailure);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('200,000 frames of plain recursion is a RangeError, not a wrong answer', recursiveFailure, 'RangeError');
test('writing it in tail position changes nothing: no engine here elides the frame', tailFailure, 'RangeError');
test('the same recursion at a shallow depth was never the problem', shallowStillFine, [5050, 5050, 5050]);
test('the loop returns the answer the recursion could not reach', sumLoop(DEPTH), 20000100000);
test('an explicit stack reproduces the recursive pre-order exactly', [smallStack, smallStack.join() === smallRecursive.join()], [[1, 2, 4, 5, 3], true]);
test('pushing children in source order reverses siblings, because pop is last-in-first-out', smallForwardPush, [1, 3, 2, 5, 4]);
test('50,000 deep, the recursive walk dies and the stack walk returns every node', [deepRecursive, deepStackFacts.slice(0, 3)], ['RangeError', [50000, 1, 50000]]);
test('and it never held more than one node, because the heap grows, not the call stack', deepStackFacts[3], 1);
test('a trampoline flattens mutual recursion that no single rewrite could', [isEvenSafely(100000), isEvenSafely(99999), mutualFailure], [true, false, 'RangeError']);

Recursion depth is a hard resource limit, not a style preference. Each call needs a frame, the stack is a fixed allocation of a megabyte or so, and the ceiling lands somewhere around ten thousand frames — engine-dependent, which is why the assertions here check for a RangeError rather than a number. The failure mode is the nasty part: it depends on the size of the input, so it passes every test written against a small fixture and throws the first time real data arrives.

The tail-call assertion is the one to remember. ES6 specified proper tail calls, and outside JavaScriptCore nobody shipped them, so rewriting n + f(n-1) as f(n-1, acc+n) buys you nothing at all in V8 or SpiderMonkey. Advice to "make it tail recursive" is advice from another language. What actually works is moving the pending work off the call stack and onto the heap, where the only limit is memory: a loop for linear recursion, an explicit array as a stack for tree recursion, or a trampoline where the recursion is mutual and no single rewrite reaches it.

The explicit stack is worth getting exactly right, and the two walk orders show why. Recursion visits children left to right; an array used as a stack pops the last thing pushed, so pushing children in source order visits them backwards — [1, 3, 2, 5, 4] instead of [1, 2, 4, 5, 3]. Push in reverse and the order matches the recursion node for node. The high-water assertion is the payoff: walking a 50,000-deep chain, the array never held more than one node, while the recursive version needed 50,000 live frames to do the same work. Swap pop for shift and the same five lines become a breadth-first walk, which is a queue rather than a stack, and something plain recursion cannot express at all.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.