function factorialRecursive(n) {
if (n === 0) return 1;
return n * factorialRecursive(n - 1);
}
function factorialIterative(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorialRecursive(5));
console.log(factorialIterative(5));Both recursive and iterative functions correctly compute factorial(5) = 120.
Recursive calls multiply 5 * 4 * 3 * 2 * 1 = 120.
Iterative loop multiplies from 1 to 5, also 120.
Recursion is ideal for problems like tree traversal or divide-and-conquer where the problem splits into smaller subproblems.
Iteration is better for simple repeated tasks without nested calls.
function fibMemo(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
return memo[n];
}
console.log(fibMemo(7));fibMemo(7) returns the 7th Fibonacci number starting from 0 index.
Sequence: 0(0),1(1),2(1),3(2),4(3),5(5),6(8),7(13).
function sumRecursive(arr) {
if (arr.length === 0) return 0;
return arr[0] + sumRecursive(arr.slice(1));
}
console.log(sumRecursive([1,2,3]));The function correctly sums the array elements recursively.
sumRecursive([1,2,3]) = 1 + sumRecursive([2,3]) = 1 + 2 + 3 = 6.
JavaScript has limited call stack size, so deep recursion can cause stack overflow.
Iteration uses loops and avoids deep call stacks, making it safer for large depths.
