A recursive function solves a problem by solving a smaller version of it and combining. It needs a base case that is answered directly, or it recurses forever: factorial(0) is 1, factorial(n) is n * factorial(n - 1). Each call waits for the smaller one, so JavaScript limits the depth to some thousands of calls.
Recursion suits nested structures, like arrays that contain arrays: to flatten one, walk the items and flatten any item that is itself an array (Array.isArray tells you). The built-in arr.flat(Infinity) does this too; writing it once is the point.
function countDown(n) {
if (n === 0) return [];
return [n, ...countDown(n - 1)];
}
console.log(countDown(3)); // [3, 2, 1]Your task
Write factorial(n), fib(n) returning the nth Fibonacci number with fib(0) = 0 and fib(1) = 1, and flatten(nested) turning arrays nested to any depth into one flat array, without using .flat().
Hint 1
if (n <= 1) return 1; return n * factorial(n - 1);
Hint 2
if (Array.isArray(item)) result.push(...flatten(item)); else result.push(item);
Show the solution
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
function flatten(nested) {
const result = [];
for (const item of nested) {
if (Array.isArray(item)) result.push(...flatten(item));
else result.push(item);
}
return result;
}