Consider this JavaScript function that calls itself recursively without a proper stop condition. What will happen when we run countdown(5)?
function countdown(n) { console.log(n); countdown(n - 1); } countdown(5);
Think about what happens when the function never stops calling itself.
The function calls itself with decreasing numbers but never stops. Eventually, JavaScript runs out of space to keep track of calls and throws a RangeError due to stack overflow.
Which of the following best describes what causes a stack overflow error in JavaScript?
Think about what happens when functions keep calling themselves endlessly.
A stack overflow happens when the call stack grows too large, usually because functions call themselves without stopping, exhausting memory reserved for calls.
Look at this factorial function. What will factorial(5) return?
function factorial(n) { if (n === 0) return 1; return n * factorial(n - 1); } console.log(factorial(5));
Factorial of 5 is 5 * 4 * 3 * 2 * 1.
The function correctly uses a base case (n === 0) to stop recursion. It calculates 5! = 120.
This function calls itself without a base case. What error will appear when running infinite()?
function infinite() { return infinite(); } infinite();
Think about what happens when a function calls itself endlessly without stopping.
The function calls itself endlessly without a base case, causing the call stack to overflow and throw a RangeError.
Which of these is the best way to avoid stack overflow errors in recursive JavaScript functions?
Think about what stops a recursive function from calling itself forever.
A base case is a condition that stops recursion. Without it, the function calls itself endlessly, causing stack overflow.