What Is Recursion in Programming? Explained With Examples
Recursion is when a function calls itself to solve a smaller version of the same problem. Learn base cases, the call stack, and a factorial example.
Published September 22, 2026
Recursion is when a function calls itself on a smaller version of the problem until it hits a base case that stops the calls. Every recursive function needs a base case and progress toward it.
The concept
Two parts: the base case returns an answer directly, and the recursive case reduces the problem and calls the function again.
Each call is pushed onto the call stack, so very deep recursion causes a stack overflow. Some recursion can be rewritten as loops.
factorial(4) unwinding
- factorial(4) = 4 × factorial(3)
- factorial(3) = 3 × factorial(2)
- factorial(2) = 2 × factorial(1); factorial(1) = 1 (base case)
- Results return back up: 2 → 6 → 24
Practical examples
Factorial
const fact = (n) => n <= 1 ? 1 : n * fact(n - 1)
fact(5) // 120Sum of a nested array
const sum = (a) => a.reduce((t, x) => t + (Array.isArray(x) ? sum(x) : x), 0)Memoised Fibonacci
const memo = new Map()
const fib = (n) => n < 2 ? n : memo.get(n) ?? (memo.set(n, fib(n-1) + fib(n-2)), memo.get(n))Walking a tree
function walk(node) {
if (!node) return
walk(node.left); console.log(node.val); walk(node.right)
}Common mistakes
- Missing or unreachable base case → infinite recursion.
- Recomputing the same values (naive Fibonacci is exponential).
- Recursing too deep without tail handling or iteration.
Key takeaways
- Base case + smaller subproblem.
- Stack depth is limited.
- Memoise overlapping subproblems.
FAQ
Recursion vs loop?
Loops are cheaper; recursion is clearer for trees and divide-and-conquer.
What is tail recursion?
A call that is the last action, which some languages optimise into a loop; JavaScript engines generally do not.