Intermediate
22 min
Full Guide
Recursion
Recursive thinking, base cases, and recursive problem solving
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 (stop condition) and recursive case.
Classic Examples
Factorial
function factorial(n) {
if (n <= 1) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
console.log(factorial(5)); // 120Fibonacci
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// With memoization for better performance
function fibMemo(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
return memo[n];
}Sum Array
function sumArray(arr) {
if (arr.length === 0) return 0;
return arr[0] + sumArray(arr.slice(1));
}Reverse String
function reverseString(str) {
if (str.length <= 1) return str;
return reverseString(str.slice(1)) + str[0];
}Power Function
function power(base, exp) {
if (exp === 0) return 1;
return base * power(base, exp - 1);
}Tips: Always define base case first | Watch for stack overflow | Consider iterative alternatives for efficiency