Skip to the content

What recursion is

JavaScript · Unit 11: Recursion

A function can call itself. That's called recursion.

countdown prints a number and then calls itself with one less. When it reaches 0, it stops calling itself: it prints the liftoff and ends.

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

Prints

3
2
1
Liftoff!

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Multiple choice

    What is the base case of clap?

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    What does this code print?

  5. 5. Complete the code

    Fill in the factorial so it prints 120 (5 × 4 × 3 × 2 × 1).

  6. 6. Find the bug

    This program should print 6 (3 + 2 + 1). Which line has the error?

  7. 7. Put the lines in order

    Put the factorial function in order so factorial(4) gives 24.

  8. 8. Multiple choice

    What does the function f do?

  9. 9. Find the case that fails

    factorial(n) should return the factorial of n. The factorial of 0 is 1. Which call breaks it?

  10. 10. Predict the output

    This function adds up the digits of a number. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →