Call stack behavior in Javascript - Time & Space Complexity
When functions call other functions, the call stack keeps track of them. Understanding how this stack grows helps us see how the program's work increases.
We want to know how the number of function calls affects the total steps the program takes.
Analyze the time complexity of the following code snippet.
function countdown(n) {
if (n <= 0) return;
countdown(n - 1);
}
countdown(5);
This code calls itself repeatedly, counting down from n to 1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive function calls to countdown.
- How many times: Exactly n times, once for each number down to one.
Each time n increases by 1, the function calls itself one more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls |
| 100 | 100 calls |
| 1000 | 1000 calls |
Pattern observation: The number of calls grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the total steps grow in a straight line with the input size.
[X] Wrong: "Recursive calls happen all at once, so time stays the same no matter n."
[OK] Correct: Each call waits for the next one to finish, so calls add up one after another, increasing total time.
Understanding how the call stack grows with recursion helps you explain function behavior clearly and shows you can think about program steps carefully.
"What if countdown called itself twice each time? How would the time complexity change?"