Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Recursion

Recursion is a technique where a function calls itself to solve a smaller version of a problem.

It is powerful for nested structures and divide-and-conquer problems.

Why We Need It

Some problems are naturally recursive, such as tree traversal and hierarchical data.

Understanding recursion helps you choose the right approach for complex tasks.

Syntax

function fn(n) {
  if (base) return value;
  return fn(n - 1);
}

Basic Example

1. Factorial

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(5));

Base case stops at n <= 1.

Real World Example

2. Sum array

function sum(arr, i = 0) {
  if (i === arr.length) return 0;
  return arr[i] + sum(arr, i + 1);
}

console.log(sum([1, 2, 3]));

Recursively accumulate array values.

Multiple Use Cases

Base Case

Recursion is when a function calls itself.

A base case stops the recursion to prevent infinite calls.

Divide and Conquer

Recursion solves problems by reducing them into smaller versions.

Tree traversal, factorial, and Fibonacci are classic examples.

Performance Considerations

Recursion can be less efficient due to call stack overhead.

Use iteration for simple loops, recursion for hierarchical structures.

More Examples

3. Countdown

function countdown(n) {
  if (n === 0) return;
  console.log(n);
  countdown(n - 1);
}

countdown(3);

Reduce the input until the base case.

4. Tree traversal

const tree = { value: 1, children: [{ value: 2 }, { value: 3 }] };

function walk(node) {
  console.log(node.value);
  if (!node.children) return;
  node.children.forEach(walk);
}

walk(tree);

Recursion fits nested structures naturally.

Comparison

Without

let total = 0;
for (let i = 1; i <= 5; i++) {
  total *= i;
}

With

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

Common Mistakes and Fixes

Missing base case

Always define a clear stopping condition.

Stack overflow

Avoid deep recursion or use iteration where possible.

Mutating shared state

Prefer passing data through parameters.

Interview Questions

What is a base case?

The condition that stops recursion.

Why can recursion be slow?

Each call adds stack overhead.

When is recursion useful?

For trees, graphs, and divide-and-conquer problems.

Practice Problem

Practice: Write a recursive function to compute the sum of numbers from 1 to n.

// TODO: sumTo(n)

One Possible Solution

function sumTo(n) {
  if (n <= 1) return 1;
  return n + sumTo(n - 1);
}

console.log(sumTo(4));

Frequently Asked Questions

What is recursion?

A function calling itself to solve smaller subproblems.

Why is a base case important?

It stops recursion and prevents infinite calls.

When should I avoid recursion?

For very deep loops or performance-critical paths.

Try It Yourself

Try different values to see recursive calls in action.