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

Recursion.js

function factorial(n) {
  if (n <= 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

console.log(factorial(4));

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the function factorial already exists. This is called hoisting.
  2. JavaScript calls factorial(), with n = 4. It gets its own variables.
  3. n <= 1 is false, so the if-block is skipped.
  4. factorial calls itself with n = 3. The first call is still waiting for the answer, so now there are two factorial frames.
  5. n <= 1 is false, so the if-block is skipped.
  6. JavaScript calls factorial() #3, with n = 2. It gets its own variables.
  7. n <= 1 is false, so the if-block is skipped.
  8. JavaScript calls factorial() #4, with n = 1. It gets its own variables.
  9. n is 1: the base case. No more calls; this one can answer straight away.
  10. factorial returns 1.
  11. The answer travels back: 2 × 1 = 2.
  12. factorial returns 6.
  13. 4 × 6 = 24: the first call finishes last.
  14. factorial() has finished, so its variables are gone. It prints 24.

Common mistakes

Best practices

Key takeaways

Check yourself

factorial(3) makes how many calls in total?

Answer: 3. n = 3, 2, 1.

Without the base case?

Answer: Stack overflow error

·

More in Functions