Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive solution needs:
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
factorial(5); // 5 * 4 * 3 * 2 * 1 = 120
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return fib(n - 1) + fib(n - 2);
}
fib(10); // 55
function sum(arr) {
if (arr.length === 0) return 0;
return arr[0] + sum(arr.slice(1));
}
function flatten(arr) {
return arr.reduce((flat, item) =>
Array.isArray(item) ? flat.concat(flatten(item)) : flat.concat(item),
[]);
}
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
power(base, exp) that returns base raised to the power exp (without using Math.pow). Base case: exp === 0 → return 1.flatten(arr) that deeply flattens a nested array.#output: "2^10 = 1024 | flatten: 1,2,3,4,5".Every recursive function needs a base case that stops the recursion.