- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Recursion Explained
Recursion
Recursion Explained
Every recursive function is two things: a case small enough to answer outright, and a step that makes the problem smaller. Miss either one and it never ends.
The two parts
The base case is the input you can answer without recursing. The recursive case calls the function again on something smaller, and trusts it to work.
That trust is the part people struggle with. You do not trace the whole thing in your head. You assume the smaller call is correct and check that you combine its answer properly.
The shape, twice
javascript
function factorial(n) {
if (n <= 1) return 1 // base case
return n * factorial(n - 1) // smaller, then combine
}
function sumList(items, i = 0) {
if (i === items.length) return 0 // base case: nothing left
return items[i] + sumList(items, i + 1) // one item, plus the rest
}
console.log(factorial(5)) // 120
console.log(sumList([1, 2, 3, 4])) // 10