Recursion — Algorithms

Recursion is a function calling itself for a smaller version of the problem. It needs a base case (a stopping condition that returns an answer right away) and…

You get a present in a box. You open it, and inside is a smaller box. You open that one, and there's another box inside. You keep doing the same thing, opening a box, until you reach the smallest box, which holds the present.

A function can also call itself to solve a smaller version of its problem, just as you open the smaller box. That's called recursion. The problem keeps getting smaller until it is small enough to answer right away. Then the answers are put back together into the final answer.

Base case and recursive case

The factorial of 5, written 5!, is the product 5 × 4 × 3 × 2 × 1 = 120. That's the same as 5 × 4!, because 4! is 4 × 3 × 2 × 1. So factorial(5) only has to calculate 5 * factorial(4), and so on down to 1. This table shows all the calls:

Call What it does What it returns
factorial(5) 5 * factorial(4) 5 × 24 = 120
factorial(4) 4 * factorial(3) 4 × 6 = 24
factorial(3) 3 * factorial(2) 3 × 2 = 6
factorial(2) 2 * factorial(1) 2 × 1 = 2
factorial(1) base case 1

Read the middle column from the first row to the last: each call waits for the answer of the call in the row below it. Read the right column from the last row to the first: once factorial(1) answers 1, that answer is used by the call above it, one by one.

This is the code in JavaScript:

function factorial(n) {
  if (n <= 1) return 1; // base case
  return n * factorial(n - 1); // recursive case
}

console.log(factorial(5)); // 120
console.log(factorial(0)); // 1

The call stack: a pile of calls

JavaScript records every call that hasn't finished on the call stack (a pile of calls). factorial(5) is waiting for the answer from factorial(4), so factorial(4) goes on top of it, and so on. The call on top is the base case, factorial(1). That call finishes first, then the pile shrinks one call at a time.

Guess first: if you delete the base case line from factorial, do you get 0, do you get undefined, or does the program crash (stop with an error)? The answer: it crashes. Without a base case, no call can ever finish. factorial keeps calling itself (5, 4, 3, 2, 1, going down past 0 to -1, -2, ...) until the stack is full. The program then stops with a stack overflow error (the stack has overflowed). In Chrome the message is RangeError: Maximum call stack size exceeded, and in Firefox InternalError: too much recursion. The same happens when the base case is never reached. For example, if the base case is if (n === 1) and you call factorial(0), 0 goes down to -1, -2, and is never equal to 1.

The call stack has a limit, roughly 10,000 calls, depending on the browser and the function. Recursion a million calls deep still crashes even with a correct base case. So for counts that long, use a loop.

Counting down and adding up

Here are two more recursive functions, countDown and sum:

function countDown(n) {
  if (n === 0) return; // stop at 0
  console.log(n);
  countDown(n - 1); // call again with a smaller number
}

countDown(3); // 3, then 2, then 1

function sum(n) {
  if (n <= 0) return 0;
  return n + sum(n - 1);
}

console.log(sum(4)); // 10

countDown returns nothing: return; with no value means stop here. countDown prints n, then calls countDown(n - 1), until n becomes 0. sum(4) is 4 + 3 + 2 + 1 + 0 = 10. It's the same pattern as factorial, only * becomes +, and the base case returns 0.

Fibonacci: two base cases

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... Each number is the sum of the two before it. The numbering starts at 0, like an array index: fibonacci(0) = 0, fibonacci(1) = 1, fibonacci(6) = 8, fibonacci(10) = 55. This is the recursive function:

function fibonacci(n) {
  if (n === 0) return 0;
  if (n === 1) return 1;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // 8

Each call steps down to both n - 1 and n - 2, so it needs two base cases. With a base case for 0 only, fibonacci(1) would call fibonacci(-1), which never reaches a base case. With only if (n <= 1) return 1, fibonacci(0) becomes 1, but it should be 0. The two base case lines in that code can be shortened to if (n <= 1) return n;.

⚠️ undefined, a crash, or painfully slow

TL;DR: Recursion is a function calling itself for a smaller version of the problem. It needs a base case (a stopping condition that returns an answer right away) and a recursive case (return a call to itself with a smaller number). Calls that haven't finished wait on the call stack (a pile of calls). Without a base case, the stack fills up and the program crashes (stack overflow). factorial(n), the product n × (n - 1) × ... × 1, is n * factorial(n - 1) with factorial(0) = 1. fibonacci(n) is fibonacci(n - 1) + fibonacci(n - 2): each number is the sum of the two before it. It has two base cases: 0 for n = 0 and 1 for n = 1.

⚡ Base case and recursive case

Write:

function factorial(n) {
  if (n <= 1) return 1; // base case
  return n * factorial(n - 1); // recursive case
}

console.log(factorial(5)); // 120
console.log(factorial(0)); // 1

Meaning: factorial(n) calculates the product n × (n - 1) × ... × 1 by calling itself. This is called recursion. The base case n <= 1 is the stopping condition: it answers right away without calling itself again. The recursive case calls itself with a smaller number, n - 1. The return in front is a must. Without return, the result is undefined.

⚡ The call stack

Guess first: if you delete the base case line from factorial, do you get 0, do you get undefined, or does the program crash (stop with an error)?

It crashes. No call can ever finish, so the call stack (where JavaScript records the calls that haven't finished) fills up. This error is called a stack overflow. In Chrome the message is RangeError: Maximum call stack size exceeded.

Meaning: Calls that haven't finished pile up on the call stack, and a new call goes on the top. The call on top, the base case, finishes first. Then its answer is used by the call below it, one by one.

⚡ Fibonacci: two base cases

Write:

function fibonacci(n) {
  if (n === 0) return 0;
  if (n === 1) return 1;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // 8

Meaning: The Fibonacci sequence, from number 0 to number 6: 0, 1, 1, 2, 3, 5, 8. Each number is the sum of the two before it. Each call steps down to both n - 1 and n - 2, so it needs two base cases: one for 0 and one for 1. This version is slow for big n: fibonacci(30) already takes about 2.7 million calls.

What you will learn