What is Recursion?
Recursion is when a function calls itself to solve smaller instances of the same problem. Every recursive function needs a base case to stop the recursion and prevent infinite loops.
Recursion is useful for solving problems that have a naturally recursive structure, like tree traversal or mathematical calculations.
Basic Recursion
// Simple recursion - countdown
function countdown(n) {
if (n <= 0) {
console.log("Done!");
return; // BASE CASE - stop recursion
}
console.log(n);
countdown(n - 1); // RECURSIVE CALL
}
countdown(3);
// Output:
// 3
// 2
// 1
// Done!
// Recursion with return value
function factorial(n) {
if (n <= 1) {
return 1; // BASE CASE
}
return n * factorial(n - 1); // RECURSIVE CALL
}
console.log(factorial(5)); // 120 (5*4*3*2*1)
console.log(factorial(0)); // 1Recursion needs a base case to avoid infinite loops. The function calls itself with a simpler input.