Algorithms and Data Structures · Junior · Question 27 of 75
What happens when you call this function?
function countdown(n) {
console.log(n);
countdown(n - 1);
}
countdown(3);- ✓Correct answer: It never stops and crashes with a stack overflow
- 2It prints 3, 2, 1 and then returns normally
- 3It prints 3, 2, 1, 0 and then returns
Explanation
There is no base case such as if (n === 0) return, so the function goes into negative numbers and keeps calling itself. Each call takes a stack frame, and eventually the stack overflows.