Recursion
Solve a problem by having a function call itself on a smaller version of the same problem.
- Identify the base case before writing the recursive case.
- Trace the call stack by hand for a small input.
- Decide between a loop and recursion by the shape of the problem.
In plain English
Recursion is a technique where a function calls itself to solve a smaller version of the same problem. The base case is the simplest input the function can solve without another call, and it is what makes the recursion stop. The recursive case is the branch where the function calls itself with a smaller input, moving toward the base case. The call stack is a hidden list the computer uses to remember where each call must return to, and it grows deeper with every recursive call. Recursion reads clearly for problems that are naturally nested, such as a factorial or a tree, while a loop is usually simpler for a flat list you walk once.
Step by step
- 1Write the base case that returns 1 when n is 1 or less.
- 2Write the recursive case that returns n times factorial(n - 1).
- 3Trace factorial(3) by hand and watch each call pile onto the call stack.
- 4Watch the calls unwind as each one returns and the stack shrinks.
function factorial(n) {
if (n <= 1) return 1
return n * factorial(n - 1)
}
console.log(factorial(5))Common mistakes
- Forgetting a base case makes the function call itself forever and eventually crash with a stack overflow.
- Returning factorial(n) without shrinking n keeps calling with the same input, so it never reaches the base case.
- Assuming the function jumps straight to the smallest case is wrong, because the calls pile up before any of them can return.
- Using recursion for a simple flat loop over a large array can overflow the call stack and is often harder to read.
Sum a range recursively
Write a recursive function sumTo that returns the sum of every whole number from n down to 1.
function sumTo(n) {}What is the purpose of a base case in a recursive function?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.