Recursion
A recursive function solves a problem by calling itself on a smaller piece. It needs a base case that stops the calls, or it will run until the browser reports a stack overflow.
Example
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5));
function countdown(n) {
if (n === 0) {
console.log("Go!");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);Exercise
Name the part that stops the recursion.
if (n <= 1) return 1; // the case
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.