Labs ICT
Pro Login

What is Recursion? A Plain English Explanation

General Concepts Explained 6 min read

Recursion is a function that calls itself. Learn what it is, when to use it, and how to avoid common mistakes.

What is Recursion? A Plain English Explanation

Recursion sounds complicated, but it's a simple concept: a function that calls itself. It's like looking into a mirror facing another mirror — the same image repeats infinitely.

A Simple Analogy

Imagine you're in a line at a bank and ask "how many people are in front of me?" The person ahead asks the same question to the person in front of them. This keeps going until someone finds no one ahead — they answer "zero." Then each person adds one and passes the answer back. That's recursion.

How Recursion Works

Every recursive function needs two parts:

  1. Base case — When to stop (the person at the front of the line)
  2. Recursive case — When to repeat (each person asking the next)
// A recursive function
function countDown(n) {
  // Base case
  if (n === 0) {
    console.log("Done!");
    return;
  }
  // Recursive case
  console.log(n);
  countDown(n - 1); // Call itself
}

countDown(5); // 5, 4, 3, 2, 1, Done!

Recursion vs Iteration

You can solve most problems with recursion or loops. Here's the same problem both ways:

// With recursion
function factorial(n) {
  if (n === 1) return 1;
  return n * factorial(n - 1);
}

// With a loop
function factorial(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

Both give the same answer. Recursion is sometimes cleaner, loops are sometimes faster.

When to Use Recursion

  • Trees and graphs — Navigating hierarchical data
  • Divide and conquer — Breaking problems into smaller pieces
  • Sorting algorithms — Quick sort, merge sort
  • Mathematical problems — Factorials, Fibonacci sequence

The Danger: Stack Overflow

Each recursive call uses memory. If you recurse too deep, you run out of memory. That's a stack overflow error. Always make sure your base case is reachable.

// BAD: No base case, infinite recursion
function forever(n) {
  return forever(n + 1); // Never stops!
}

// GOOD: Base case stops recursion
function sum(n) {
  if (n === 0) return 0; // Base case
  return n + sum(n - 1);
}

Note: Recursion takes practice to understand. Start with simple examples, trace through the function calls by hand, and you'll see the pattern.