When not to use it
JavaScript · Unit 11: Recursion
- Full plan
- JavaScript
- 10 exercises
Every waiting call takes up a spot on the stack, and the stack has a limit. If a function calls itself nonstop, the stack fills up and JavaScript crashes with a RangeError.
Its message says "Maximum call stack size exceeded": the stack went over its maximum size.
function forever(n) {
return forever(n + 1);
}
try {
forever(1);
} catch (error) {
console.log(error.name);
}Prints
RangeError
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 happens with
countdown(5)?3. Find the bug
This program should print 8 (2 × 2 × 2). Which line has the error?
4. Multiple choice
sumUpTo(100000)crashes, butsumUpTodoes have a base case. Why does it crash?5. Complete the code
Fill in the factorial with a loop so it prints 120.
6. Predict the output
This is how you flip a string with a loop. What does it print?
7. Put the lines in order
Put
powerin order using a loop, with no recursion, sopower(2, 3)gives 8.8. Find the case that fails
sumUpTo(n)should add from 1 ton, or give 0 ifnis 0 or negative. Which call breaks it?9. Multiple choice
In which of these cases is recursion a better fit than a loop?
10. Predict the output
In the Fibonacci sequence, each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8… This function counts its own calls. 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.