← Back to JavaScript, page 4

javascript-0063 · Easy fresher

What is recursion, what are the base case and the recursive case, and what happens if the base case is missing?

Recursion is a function calling itself on a smaller version of the problem. It needs a base case that stops the calls and a recursive case that moves toward it. Each call adds a frame to the call stack, so a missing or unreachable base case ends in a RangeError for stack overflow. Some recursive solutions repeat work and are slow without memoization.

Full answer

A recursive function solves a problem by solving a smaller copy of the same problem. Two parts are required.

The base case is the simplest input, answered directly, and it stops the recursion. For factorial, factorial(0) is 1. The recursive case reduces the input and calls the function again, and uses the result: n * factorial(n - 1). Every chain of calls must move toward the base case.

Each call gets its own frame on the call stack, holding its parameters and local variables. The frames pile up until the base case returns, and then they unwind one by one as each result is combined. The stack has a limited size. A function that never reaches its base case, or a very deep input, throws RangeError: Maximum call stack size exceeded. The limit is typically around ten thousand frames, and it depends on the engine and on frame size.

Recursion fits problems that are naturally nested or self-similar: walking a folder tree, flattening nested arrays, parsing expressions, and divide-and-conquer algorithms. For simple counting loops, an iterative version uses constant stack space and is usually clearer.

Careless recursion can repeat work. The naive Fibonacci function calls itself twice, so it recomputes the same values thousands of times and takes exponential time. Remembering results (memoization) or looping removes the waste.

Engines in the JavaScript specification can optimize tail calls, but in practice only Safari implements this, so do not rely on it for deep recursion.

javascript
function factorial(n) {
  if (n <= 1) return 1; // base case
  return n * factorial(n - 1); // recursive case
}
console.log(factorial(5), factorial(0));

function sumNested(list) {
  let total = 0;
  for (const item of list) {
    total += Array.isArray(item) ? sumNested(item) : item;
  }
  return total;
}
console.log(sumNested([1, [2, [3, 4]], 5]));

function countdown(n) {
  if (n === 0) return 'done';
  return countdown(n - 1);
}
console.log(countdown(1000));

function withoutBaseCase(n) {
  return withoutBaseCase(n + 1);
}
try {
  withoutBaseCase(0);
} catch (error) {
  console.log(error.name, '-', error.message);
}

let calls = 0;
function fib(n) {
  calls += 1;
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(20), 'calls:', calls);

const memo = new Map();
let memoCalls = 0;
function fastFib(n) {
  memoCalls += 1;
  if (n < 2) return n;
  if (memo.has(n)) return memo.get(n);
  const value = fastFib(n - 1) + fastFib(n - 2);
  memo.set(n, value);
  return value;
}
console.log(fastFib(20), 'calls:', memoCalls);

const folder = { name: 'root', children: [{ name: 'a', children: [{ name: 'a1', children: [] }] }, { name: 'b', children: [] }] };
const names = (node) => [node.name, ...node.children.flatMap(names)];
console.log(names(folder));

Run with Node.js v24.22.1 as js-63.js; two runs gave identical output. Output: 120 1 15 done RangeError - Maximum call stack size exceeded 6765 calls: 21891 6765 calls: 39 [ 'root', 'a', 'a1', 'b' ]

Key points

  • Every recursive function needs a base case and a recursive case that moves toward it.
  • Each call adds a stack frame; too many throws a RangeError.
  • Recursion suits nested or self-similar data such as trees.
  • Naive recursion can repeat work, as in Fibonacci; memoization fixes it.
  • Do not rely on tail call optimization in JavaScript.

Common mistakes

  • Forgetting the base case, or writing one the input can never reach.
  • Using naive recursive Fibonacci for large n.
  • Using recursion for a plain counting loop where iteration is simpler.
  • Assuming JavaScript removes tail calls automatically.

Follow-ups

  • How would you convert a recursive function into a loop with an explicit stack?
  • How deep can recursion go in your runtime, and what decides the limit?
  • What is the time complexity of naive and memoized Fibonacci?

Tips

  • State the two parts, base case and recursive case, before writing code.
  • Mention the stack and the RangeError; it shows you know what happens underneath.
  • Offer memoization when Fibonacci appears; interviewers expect it.