Recursion and Recursive Data
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Write a recursive function with a clear base case and progress toward it.
- Walk nested arrays and objects safely.
- Decide when to replace recursion with an explicit stack.
Overview
#Base case and progress
A recursive function calls itself on a smaller input and stops at a base case. Two rules keep it correct: the base case must be reachable, and every call must move the input closer to it. Missing either rule produces infinite recursion and a stack overflow.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
Recursive data
Trees, nested arrays and linked structures are naturally recursive. A depth-first walk visits a node, then recurses into its children. Passing an accumulator avoids shared mutable state.
function flatten(value) {
if (!Array.isArray(value)) return [value];
return value.flatMap(flatten);
}
console.log(flatten([1, [2, [3]]])); // [1, 2, 3]
Stack limits and iteration
Each pending call holds a frame on the call stack. Deep recursion can overflow, and JavaScript does not guarantee tail-call optimization. When depth is large or data is untrusted, convert the recursion into a loop with an explicit stack array. For overlapping subproblems, add memoization so each state is computed once.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptfunction count(n) { if (n === 0) return 0; return 1 + count(n - 1); } console.log(count(4));Exercise 2Explain
Explain what happens when a recursive function has no base case.
starter.textfunction loop(n) { return loop(n + 1); }Reveal the reference answer
reference.textEvery call pushes a new frame on the call stack and none of them return, so the stack grows until the engine runs out of space and throws a RangeError about the maximum call stack size. There is no result because the function never reaches a return. A base case is what lets the calls unwind.Authored expected output: RangeError: Maximum call stack size exceeded
The answer should describe unbounded frame growth and the resulting RangeError, and connect it to the missing stop condition.
Exercise 3Implement
Implement `deepSum(value)` so it sums every number in a nested array. Running `console.log(deepSum([1, [2, [3, 4]], 5]))` should print `15`.
starter.javascriptfunction deepSum(value) { // your code here }Reveal the reference answer
reference.javascriptfunction deepSum(value) { if (Array.isArray(value)) { return value.reduce((acc, item) => acc + deepSum(item), 0); } return typeof value === 'number' ? value : 0; }Authored expected output: 15
An array recurses into each element and adds the results, while a number contributes itself. The base cases are the number and any non-numeric value.
Exercise 4Debug
This flatten is meant to handle nested arrays but overflows on deep input. Rewrite it to use an explicit stack.
starter.javascriptfunction flatten(value) { if (!Array.isArray(value)) return [value]; return value.flatMap(flatten); } console.log(flatten([1, [2, [3]]]));Reveal the reference answer
reference.javascriptfunction flatten(value) { const out = []; const stack = [value]; while (stack.length > 0) { const current = stack.pop(); if (Array.isArray(current)) { for (let i = current.length - 1; i >= 0; i--) stack.push(current[i]); } else { out.push(current); } } return out; } console.log(flatten([1, [2, [3]]]));Authored expected output: [1, 2, 3]
The recursive version uses one stack frame per level. The loop keeps the pending items in a plain array instead, so depth is limited by memory rather than the call stack. Pushing children in reverse preserves left-to-right order.
Exercise 5Test
Write assertions that prove a memoized Fibonacci returns correct values and computes each state once.
starter.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); }Reveal the reference answer
reference.javascriptfunction fib(n, memo = new Map()) { if (n < 2) return n; if (memo.has(n)) return memo.get(n); const value = fib(n - 1, memo) + fib(n - 2, memo); memo.set(n, value); return value; } assertEqual(fib(0), 0, 'fib 0'); assertEqual(fib(1), 1, 'fib 1'); assertEqual(fib(10), 55, 'fib 10'); console.log('all assertions passed');Authored expected output: all assertions passed
Memoization stores each result in a Map keyed by n, so the exponential recursion collapses to linear work and the base cases stay correct.
Exercise 6Interview
When would you avoid recursion in production code?
Reveal the reference answer
reference.textI avoid it when the input depth is unbounded or comes from a user, because a deep tree can overflow the call stack and crash the process. I also avoid it when JavaScript cannot guarantee tail-call optimization and the recursion is on a hot path. In those cases I use an explicit stack or a queue, and I keep recursion for cases where the depth is small and the recursive shape matches the data.The answer should name stack limits, untrusted depth and the absence of guaranteed tail-call optimization, and offer an iterative alternative.
Common misconceptions
#- JavaScript engines always optimize tail-recursive calls.
- A recursive function only needs a base case, not progress toward it.
- Recursion is always slower than iteration.
Follow-up practice
#- javascript-foundations-arrays-and-iteration
- javascript-foundations-performance-and-memory
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.