Recursion
In one line
Recursion is when a function calls itself to solve a smaller version of the same problem until a base case is reached.
In simple words
Recursion is a technique where a function solves a problem by calling itself with a smaller or simpler input. Each recursive call breaks the problem down until it reaches a base case — a simple version that can be solved directly without recursion.
Think of recursion like Russian nesting dolls. You open a doll to find a smaller doll inside, and keep opening until you reach the smallest doll that cannot be opened further. That smallest doll is the base case.
Recursion is elegant for problems that have a self-similar structure: factorial, Fibonacci, tree traversal, directory listing. However, each recursive call adds to the call stack, so deep recursion can cause a stack overflow. Iteration is usually more efficient for simple repetition.
Example
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
console.log(factorial(5)); // 120factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = ... = 5 * 4 * 3 * 2 * 1 = 120. The base case (n <= 1) stops the recursion.
Common confusions
Confused with: loop
The difference: A loop repeats code using iteration (for/while); recursion repeats by a function calling itself. Loops are usually more efficient; recursion can be clearer for tree-structured problems.
Related terms
Related Resources
Related Lessons
- Recursion
Learn about recursive functions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.