Base Case
Recursion is when a function calls itself.
A base case stops the recursion to prevent infinite calls.
JavaScript Tutorial
Recursion is a technique where a function calls itself to solve a smaller version of a problem.
It is powerful for nested structures and divide-and-conquer problems.
Some problems are naturally recursive, such as tree traversal and hierarchical data.
Understanding recursion helps you choose the right approach for complex tasks.
function fn(n) {
if (base) return value;
return fn(n - 1);
}function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5));Base case stops at n <= 1.
function sum(arr, i = 0) {
if (i === arr.length) return 0;
return arr[i] + sum(arr, i + 1);
}
console.log(sum([1, 2, 3]));Recursively accumulate array values.
Recursion is when a function calls itself.
A base case stops the recursion to prevent infinite calls.
Recursion solves problems by reducing them into smaller versions.
Tree traversal, factorial, and Fibonacci are classic examples.
Recursion can be less efficient due to call stack overhead.
Use iteration for simple loops, recursion for hierarchical structures.
function countdown(n) {
if (n === 0) return;
console.log(n);
countdown(n - 1);
}
countdown(3);Reduce the input until the base case.
const tree = { value: 1, children: [{ value: 2 }, { value: 3 }] };
function walk(node) {
console.log(node.value);
if (!node.children) return;
node.children.forEach(walk);
}
walk(tree);Recursion fits nested structures naturally.
Without
let total = 0;
for (let i = 1; i <= 5; i++) {
total *= i;
}With
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}Always define a clear stopping condition.
Avoid deep recursion or use iteration where possible.
Prefer passing data through parameters.
The condition that stops recursion.
Each call adds stack overhead.
For trees, graphs, and divide-and-conquer problems.
Practice: Write a recursive function to compute the sum of numbers from 1 to n.
// TODO: sumTo(n)
One Possible Solution
function sumTo(n) {
if (n <= 1) return 1;
return n + sumTo(n - 1);
}
console.log(sumTo(4));A function calling itself to solve smaller subproblems.
It stops recursion and prevents infinite calls.
For very deep loops or performance-critical paths.
Try different values to see recursive calls in action.