What is recursion? Give an example.

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Functions #JS Basics

Brief Answer

Recursion is when a function calls itself. This can solve problems that repeat at each step but become simpler. Classic example — calculating factorial of a number. 🔁

A function that calls itself:

function countDown(n) {
  if (n <= 0) return;
  console.log(n);
  countDown(n - 1); // Calling itself
}

Full Answer

Recursion is a powerful programming technique where a function calls itself. This might seem strange, but it’s very useful for certain tasks. 😊

What is Recursion

A function that calls itself:

function countDown(n) {
  if (n <= 0) return;
  console.log(n);
  countDown(n - 1); // Calling itself
}

How Recursion Works

Base Case

function factorial(n) {
  // Base case — stopping recursion
  if (n <= 1) return 1;
  
  // Recursive case
  return n * factorial(n - 1);
}

Call Stack

// factorial(3) creates stack:
// factorial(3) → 3 * factorial(2)
// factorial(2) → 2 * factorial(1)
// factorial(1) → 1 (base case)

Simple Examples

Calculating Power

function power(base, exponent) {
  if (exponent === 0) return 1;
  return base * power(base, exponent - 1);
}
 
console.log(power(2, 3)); // 8 ✅

Traversing Nested Structures

const tree = {
  value: 1,
  children: [
    { value: 2, children: [] },
    { value: 3, children: [{ value: 4, children: [] }] }
  ]
};
 
function sumTree(node) {
  let sum = node.value;
  for (let child of node.children) {
    sum += sumTree(child); // Recursive call
  }
  return sum;
}

Important Features

1. Base Case

function recursive(n) {
  // ❌ Without base case — infinite recursion
  // return recursive(n); // Stack overflow!
  
  // ✅ With base case
  if (n <= 0) return; // Stopping
  return recursive(n - 1);
}

2. Memory

// Each call takes space in stack
// Too many calls — stack overflow error

Where Recursion is Used

Working with Trees

// Traversing folders and files
function scanDirectory(dir) {
  console.log(dir.name);
  for (let item of dir.children) {
    if (item.isDirectory) {
      scanDirectory(item); // Recursive traversal
    }
  }
}

Algorithms

// Quick sort
function quickSort(arr) {
  if (arr.length <= 1) return arr;
  
  const pivot = arr[0];
  const less = arr.slice(1).filter(x => x <= pivot);
  const greater = arr.slice(1).filter(x => x > pivot);
  
  return [...quickSort(less), pivot, ...quickSort(greater)];
}

Common Mistakes

1. Missing Base Case

// ❌ Infinite recursion
function bad(n) {
  return bad(n - 1); // No stopping!
}
 
// ✅ With stopping
function good(n) {
  if (n <= 0) return; // Base case
  return good(n - 1);
}

2. Too Deep Recursion

// ❌ May cause stack overflow
function deep(n) {
  if (n <= 0) return;
  return deep(n - 1);
}
 
// deep(100000); // Error!
 
// ✅ Iteration instead of deep recursion
function iterative(n) {
  for (let i = n; i > 0; i--) {
    // Same thing, but without recursion
  }
}

Simple Rules

  1. Base case — always need stopping point 🔚
  2. Simplification — each call should move toward base case 📉
  3. Memory — recursion uses call stack 🧠
  4. Trees — perfect for hierarchical structures 🌳
  5. Simplicity — sometimes simpler than loops 🔄

Recursion is an elegant way to solve problems that repeat at different levels. But be careful with the base case! ⚠️


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪