JavaScript Recursion
Recursion is a function calling itself. Each call works on a smaller input until a base case stops the calls.
Factorial
Recursion is a function calling itself, and factorial shows the pattern. The ternary picks 1 at the base case and the product otherwise.
function factorial(n) {
return n === 0 ? 1 : n * factorial(n - 1);
}
console.log(factorial(5));Count down
tick logs its number first on each call. The ternary calls tick again with one less while the number stays above 1.
function tick(n) {
console.log(n);
n > 1 ? tick(n - 1) : null;
}
tick(3);Add a range
sumTo adds n to the sum of the smaller numbers below it. The base case adds 0 and stops the calls.
function sumTo(n) {
return n === 0 ? 0 : n + sumTo(n - 1);
}
console.log(sumTo(4));Example
function factorial(n) {
return n === 0 ? 1 : n * factorial(n - 1);
}
function tick(n) {
console.log(n);
n > 1 ? tick(n - 1) : null;
}
console.log(factorial(5));
tick(3);Key points
- Base case: the condition that stops the calls, such as n === 0
- Each recursive call passes a smaller argument than the call before it.
- The call stack is the pile of calls waiting to finish.
- Without a base case, the calls never stop and the browser reports a RangeError.
- A recursive function needs a stopping condition and a shrinking argument.
In this example, factorial calls itself with 4, then 3, then 2, then 1. The call with 0 hits the base case and returns 1. The waiting calls multiply back up to 120, and the caller logs it. The tick function then logs 3, calls itself with 2, logs 2, calls itself with 1, and logs 1 before stopping.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is the base case in a recursive function?