Tracing the calls
JavaScript · Unit 11: Recursion
- Full plan
- JavaScript
- 10 exercises
When a function calls itself, the outer call pauses and waits for the inner one to finish. Each call has its own n.
The waiting calls stack up like plates: the last one to start is the first one to finish. That's called the call stack.
function f(n) {
console.log("enter " + n);
if (n > 1) {
f(n - 1);
}
console.log("exit " + n);
}
f(3);Prints
enter 3 enter 2 enter 1 exit 1 exit 2 exit 3
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
You called
up(3). Right whileup(1)is running, how isup(3)doing?3. Predict the output
What does this code print?
4. Predict the output
What does this code print?
5. Find the bug
This program should print 10 (4 + 3 + 2 + 1). Which line has the error?
6. Complete the code
Fill in the blank so it prints 1 2 3, with the numbers in order.
7. Predict the output
A counter outside the function counts how many times it was called. What does it print?
8. Multiple choice
When
fact(4)reaches its base case, how many calls tofactare on the stack at the same time?9. Put the lines in order
Put the lines in order so it prints "Floor 1", "Floor 2" and "Floor 3", in that order.
10. Predict the output
This function calls itself twice. 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.