Problem Solving Fundamentals · Recursion

Stop the recursion

the base case

Stop the recursion

Open a set of nesting dolls far enough and you reach one that will not open. It is solid all the way through, with no smaller doll inside. That doll is what makes the stack finite: without it, you would always expect one more.

A recursive function needs the same thing — a case it answers without calling itself again. That is the base case, and it is the first thing to write, not the last, because everything else leans on it.

Take the factorial of a number. 5! means 5 × 4 × 3 × 2 × 1. Stare at it and you can see the repeat: 5! is 5 × 4!, and 4! is 4 × 3!, and so on. The step keeps the same shape on a smaller number, until you reach the smallest case that has an answer by itself. For factorial that case is 0!, which is 1 — no multiplication left to do.

Write it in that order. First the stop:

if (n <= 1) {
  return 1;
}

Then the step, trusting that the call on n - 1 already returns its answer:

return n * factorial(n - 1);

Each call hands over a smaller number, so the base case is always reachable. The mistake that costs the most time is writing the step and forgetting the stop — then the calls never end, and the program runs out of room. Name the smallest case first, and the rest falls out of it.

Export factorial from index.js. It returns the product of every whole number from 1 up to n, with 0! and 1! both equal to 1.

Challenge

A factorial multiplies a number by every whole number below it: 5! is 5 × 4 × 3 × 2 × 1. Written as a function that calls itself, it needs a case that stops.

Export a factorial function from index.js. It takes a non-negative integer n and returns n!, the product of every whole number from 1 up to n. By convention 0! and 1! are both 1. That smallest case is the one the recursion must not miss.

index.js
export function factorial(n) {
  return n;
}

export function render(mount) {
  const n = 5;

  mount.textContent = `${n}! = ${factorial(n)}`;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.