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 a technique where a function calls itself to solve a smaller instance of the same problem, continuing until reaching a 'base case' simple enough to answer directly without further recursive calls.

Common causes

  • Some problems are naturally defined in terms of themselves — a factorial, a tree traversal, or the Fibonacci sequence are each defined by a smaller version of the same problem

How to fix it

  • Always define a base case that stops the recursion — without one, the function calls itself forever until the call stack overflows
  • Make sure each recursive call moves strictly closer to the base case (e.g. n-1 instead of n), or the recursion will never terminate
  • For problems where recursion causes excessive repeated work (like naive Fibonacci), consider memoization or converting to an iterative approach

Example

function factorial(n) {
  if (n <= 1) return 1       // base case
  return n * factorial(n - 1) // recursive case
}

FAQ

What causes a 'stack overflow' in recursion?

Each recursive call adds a new frame to the call stack. Without a base case that's eventually reached (or with too many recursive calls before reaching it), the stack keeps growing until it exceeds its size limit and crashes.

More General articles