Careeroza
Recursion
Recursive Functions
Example
A recursive function calls itself on a smaller problem until it reaches a base case:
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
console.log(factorial(5));
function sumNested(arr) {
return arr.reduce((t, x) => t + (Array.isArray(x) ? sumNested(x) : x), 0);
}
console.log(sumNested([1, [2, [3, [4]]]]));Output
120 10
Walking a Tree
Example
Recursion fits naturally with nested data like menus, folders and comments:
const menu = { name: "Courses", children: [
{ name: "Web", children: [{ name: "HTML" }, { name: "CSS" }] },
{ name: "Data", children: [{ name: "SQL" }] },
] };
function print(node, depth = 0) {
console.log(" ".repeat(depth) + "- " + node.name);
for (const child of node.children ?? []) print(child, depth + 1);
}
print(menu);Output
- Courses
- Web
- HTML
- CSS
- Data
- SQL