Chapter VI · Functions
Recursion
Recursion occurs when a function calls itself repeatedly until it reaches a termination base case condition.
01 How It Works
Think of opening nested Russian nesting dolls until reaching the smallest solid core doll.
Every recursive step breaks down a large problem into a smaller sub-problem guarded by an exit condition.
example.js
function countdown(n) {
if (n <= 0) return;
console.log(n);
countdown(n - 1);
}
countdown(3);
1. Define a base case exit condition to prevent infinite loops.
2. Define the recursive step where the function calls itself with modified input.
3. Return combined cumulative results.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(4)); // 24
Key Takeaway
Recursion provides elegant solutions for hierarchical or self-similar data structures.