What recursion is
JavaScript · Unit 11: Recursion
- Full plan
- JavaScript
- 10 exercises
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. Predict the output
What does this code print?
2. Multiple choice
What is the base case of
clap?3. Predict the output
What does this code print?
4. Predict the output
What does this code print?
5. Complete the code
Fill in the factorial so it prints 120 (5 × 4 × 3 × 2 × 1).
6. Find the bug
This program should print 6 (3 + 2 + 1). Which line has the error?
7. Put the lines in order
Put the
factorialfunction in order sofactorial(4)gives 24.8. Multiple choice
What does the function
fdo?9. Find the case that fails
factorial(n)should return the factorial ofn. The factorial of 0 is 1. Which call breaks it?10. Predict the output
This function adds up the digits of a number. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.