Recursion
factorial calls itself with a smaller number until it reaches 1. Watch the call stack grow four deep, then unwind.
JavaScript · beginner · 7 min · 14 steps · free
What you'll learn
- Write a recursive function with a base case
- Follow recursive calls on the stack
Recursion.js
function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(4));
Step by step
- Before the first line runs, JavaScript reads the whole file: the function
factorial already exists. This is called hoisting. - JavaScript calls
factorial(), with n = 4. It gets its own variables. n <= 1 is false, so the if-block is skipped.- factorial calls itself with n = 3. The first call is still waiting for the answer, so now there are two factorial frames.
n <= 1 is false, so the if-block is skipped.- JavaScript calls
factorial() #3, with n = 2. It gets its own variables. n <= 1 is false, so the if-block is skipped.- JavaScript calls
factorial() #4, with n = 1. It gets its own variables. - n is 1: the base case. No more calls; this one can answer straight away.
factorial returns 1.- The answer travels back: 2 × 1 = 2.
factorial returns 6.- 4 × 6 = 24: the first call finishes last.
factorial() has finished, so its variables are gone. It prints 24.
Common mistakes
- Forgetting the base case: the stack overflows
Best practices
- Make sure every call moves towards the base case
Key takeaways
- A recursive function calls itself on a smaller problem.
- The base case stops the recursion.
- Calls pile up on the stack, then return in reverse order.
Check yourself
factorial(3) makes how many calls in total?
Answer: 3. n = 3, 2, 1.
Without the base case?
Answer: Stack overflow error
← Closures · Functions as Values: Callbacks →
More in Functions