Recursion is a programming technique where a function calls itself to solve a problem. It consists of:
Recursion is particularly useful for problems that can be broken down into smaller, similar subproblems.
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example: 5! = 5 × 4 × 3 × 2 × 1 = 120
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
Logs will appear here.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. For example: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
function fibonacci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Logs will appear here.
A simple countdown function that demonstrates recursion by counting down from a given number to 1.
function countdown(n) {
if (n <= 0) return;
console.log(n);
countdown(n - 1);
}
Logs will appear here.