Skip to content

JavaScript Recursion

  • by

Recursion in JavaScript refers to the process of a function calling itself within its own definition. It is a powerful programming technique that allows you to solve complex problems by breaking them down into smaller, similar subproblems.

function functionName(parameters) {
  // Base case(s)
  if (/* base case condition */) {
    // Return a value or perform an action
  }

  // Recursive case(s)
  // Modify the parameters or state
  // Call the function recursively
  return functionName(modifiedParameters);
}

In a recursive function, there are typically two components:

  1. Base case: This is the condition that determines when the recursion should stop. When the base case is met, the function stops calling itself and returns a specific value.
  2. Recursive case: This is the part of the function where it calls itself, typically with a modified input or state. The recursive call allows the function to solve a smaller version of the problem and move closer to the base case.

JavaScript recursion example

Simple example code of a recursive function in JavaScript that calculates the factorial of a number:

function factorial(n) {
  // Base case: factorial of 0 or 1 is 1
  if (n === 0 || n === 1) {
    return 1;
  }

  // Recursive case: multiply n by the factorial of n-1
  return n * factorial(n - 1);
}

console.log(factorial(5)); 

Output:

JavaScript Recursion

In this example, the factorial function has a base case that returns 1 when n is 0 or 1. Otherwise, it calls itself a smaller value (n - 1) and multiplies the result by n.

Another example that calculates the sum of all positive integers up to a given number:

function sumUpTo(n) {
  // Base case: when n is 1, return 1
  if (n === 1) {
    return 1;
  }

  // Recursive case: sum n with the sum of all positive integers up to n-1
  return n + sumUpTo(n - 1);
}

console.log(sumUpTo(5));  // Output: 15 (1 + 2 + 3 + 4 + 5)

Comment if you have any doubts or suggestions on this Js recursion topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *