Codiqo

Learn JavaScript · lesson 49 of 60 · about 8 minutes

Functions That Call Themselves

Solve a problem by solving a smaller copy of the same problem.

What you'll learn

  • Write a base case that stops the recursion
  • Write a recursive case that moves towards it
  • Return values from recursive calls

Counting down to the holidays

The holidays are coming, and Sam wants the page to count down to them. With more than 5 days left it just says 12 days until the holidays; in the last five days it counts down the rest, like 3... 2... 1... Holidays!. A loop could build that text, but this unit is about another way: a function that calls itself. countdown(3) is 3... followed by countdown(2), and countdown(0) is simply Holidays!.

A function inside itself

A recursive function calls itself. Each call works on a smaller piece of the problem, until the piece is so small the answer is obvious.

Every recursive function needs two parts:
- A base case that returns without calling itself
- A recursive case that calls itself on something smaller

Counting down

function countdown(n) {
  if (n === 0) {
    console.log("Lift off!");
    return;
  }
  console.log(n);
  countdown(n - 1);
}

countdown(3);

Output

3
2
1
Lift off!

Returning an answer

Recursive functions can return values too. The factorial of 4 is 4 × 3 × 2 × 1, which is the same as 4 × (the factorial of 3). So factorial(n) can return n * factorial(n - 1), with factorial(1) returning 1.

Factorial

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(4));
console.log(factorial(1));

Output

24
1

Building text on the page

A recursive function can return text as well as numbers. Each call adds its own piece in front of whatever the smaller call gives back, and the base case gives back the end of the text. Sam's countdown works the same way, with Holidays! at the end.

Stars for a rating

function stars(n) {
  if (n === 0) return "";
  return "*" + stars(n - 1);
}

document.querySelector("#rating").textContent = `Rating: ${stars(3)}`;
console.log(document.querySelector("#rating").textContent);

Output

Rating: ***

Tip

Each call must get closer to the base case. If n never reaches it, JavaScript stops with RangeError: Maximum call stack size exceeded.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.