Back to JavaScript
2025-12-175 min read

Recursion

Learn Recursion step by step with clear examples and exercises.

Title: Recursion in JavaScript - A full guide

Why This Matters

Recursion is a fundamental concept in computer science, especially in problem-solving and algorithm design. It allows us to solve complex problems by breaking them down into smaller, manageable parts, which can be solved repeatedly until the entire problem is solved. In JavaScript, recursion is used to create efficient solutions for various tasks such as traversing tree structures, sorting arrays, and calculating factorials. Understanding recursion is crucial for acing coding interviews, debugging complex code, and solving real-world programming problems.

Prerequisites

To understand recursion in JavaScript, you should be familiar with the following concepts:

  1. Basic JavaScript syntax, including variables, functions, loops, and conditional statements.
  2. Understanding of call stacks and how they work in JavaScript.
  3. Familiarity with data structures like arrays and objects.
  4. Knowledge of common algorithms and problem-solving techniques.

Core Concept

Definition

Recursion is a method used by functions to solve problems by calling themselves repeatedly, breaking the original problem into smaller subproblems until they reach a base case. The function then returns a value from the base case, which is combined with values returned from subsequent recursive calls to build the final solution.

Recursive Function Structure

A recursive function in JavaScript consists of three main parts:

  1. Base Case: This is the simplest form of the problem that can be solved directly without any further recursion. When the function encounters a base case, it returns a value and stops calling itself.
  2. Recursive Call: This is the part where the function calls itself with a smaller version of the problem. The recursive call should eventually lead to the base case.
  3. Combining Results: In some cases, the results from multiple recursive calls need to be combined to build the final solution. This can be done using variables or by returning values from recursive calls and combining them in the main function.

Example - Factorial Function

Here's an example of a simple recursive function that calculates the factorial of a number:

function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

In this example, the base case is when n equals 0 or 1. The function returns 1 for these cases. For other values of n, it calls itself with a smaller value (n - 1) and multiplies the result by n. This process continues until the base case is reached, at which point the final result is returned.

Worked Example

Let's consider an example of using recursion to find the maximum element in an array:

function findMax(arr) {
if (arr.length === 0) {
return null;
} else if (arr.length === 1) {
return arr[0];
} else {
let max = findMax(arr.slice(1));
if (arr[0] > max) {
max = arr[0];
}
return max;
}
}

In this example, the base case is when the array has no elements or just one element. For arrays with more than one element, the function first finds the maximum element in the rest of the array (arr.slice(1)) and then checks if the first element is greater than the current maximum. If it is, the first element becomes the new maximum. The process continues recursively until the base case is reached.

Common Mistakes

  1. Forgetting to define a base case: A recursive function must have a base case that stops the recursion and returns a result. Without a base case, the function will continue calling itself indefinitely, causing a stack overflow error.
  2. Incorrect recursive call arguments: The arguments passed to the recursive call should be carefully chosen to ensure they represent a smaller version of the original problem. Incorrect arguments can lead to an infinite loop or incorrect results.
  3. Not combining results correctly: If multiple recursive calls are needed to build the final solution, it's important to combine the results correctly. Failing to do so will result in incorrect solutions.
  4. Overlooking edge cases: Edge cases should be carefully considered and handled appropriately to ensure that the function works correctly for all possible inputs.

Practice Questions

  1. Write a recursive function to find the sum of the elements in an array.
  2. Implement a recursive function to reverse an array.
  3. Write a recursive function to check if a given number is prime or not.
  4. Implement a recursive binary search algorithm for finding an element in a sorted array.

FAQ

Why use recursion when iteration can be used instead?

  • Recursion can often lead to more readable and elegant solutions, especially for problems that naturally lend themselves to recursive thinking. Iteration might be preferable for simpler tasks or when performance is a concern.

What happens if there are too many recursive calls in a function?

  • If there are too many recursive calls without a base case, the function will cause a stack overflow error, as the call stack becomes too deep and runs out of memory.

How can I avoid infinite recursion in my functions?

  • To prevent infinite recursion, make sure to define a clear base case that stops the recursion when it reaches a simple enough problem that can be solved directly.

Is it always better to use recursion over iteration for complex problems?

  • While recursion can lead to more elegant solutions for certain problems, it might not always be the best choice, especially if performance is a concern or if the problem requires iterating through large amounts of data. In such cases, iteration might be a better choice.
Recursion | JavaScript | XQA Learn