Skip to content

Recursive Function JavaScript

  • by

A recursive function in JavaScript is a function that calls itself repeatedly until it reaches a base case. It is commonly used to solve problems that can be divided into smaller subproblems. This feature allows for elegant and concise solutions to certain types of problems.

The syntax for creating a recursive function.

function recursiveFunction(/* parameters */) {
  // Base case: check if the recursion should stop
  if (/* termination condition */) {
    // Return a value or perform an action
    // ...
  } else {
    // Recursive case: call the function with modified parameters
    // and make progress towards the base case
    // ...

    // Call the recursive function
    recursiveFunction(/* modified parameters */);
  }
}

However, it is important to include a terminating condition (base case) to prevent infinite recursion.

function recurse() {
    // ...
    recurse();
    // ...
}

This function will result in infinite recursion, which will eventually lead to a “Maximum call stack size exceeded” error.

To make the recursive function work correctly, you need to include a base case that defines when the recursion should stop. Without a base case, the function will continue calling itself indefinitely.

Recursive Function JavaScript 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 the number by the factorial of (n-1)
  return n * factorial(n - 1);
}

console.log(factorial(5));

Output:

Recursive Function JavaScript

Calculate the sum of n natural numbers example

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

  // Recursive case: calculate the sum of (n-1) natural numbers and add n to it
  return n + calculateSum(n - 1);
}

// Calculate the sum of the first 5 natural numbers
console.log(calculateSum(5)); // Output: 15

For example, a recursive function can be used to print the numbers from 1 to 10 like this:

function printNumbers(n) {
  if (n <= 10) {
    console.log(n);
    printNumbers(n + 1);
  }
}

printNumbers(1);

Here is another example of a recursive function that can be used to reverse a string:

function reverseString(str) {
  if (str.length <= 1) {
    return str;
  } else {
    return reverseString(str.substring(1)) + str[0];
  }
}

console.log(reverseString("Hello World")); // "dlroW olleH"

To create a recursive function, follow these steps:

  1. Define the function using the function keyword.
  2. Specify any necessary parameters within the parentheses.
  3. Implement a base case that determines when the recursion should stop. This typically involves checking for a termination condition.
  4. Inside the base case, you can either return a value or perform an action.
  5. In the recursive case, modify the parameters to make progress toward the base case.
  6. Call the recursive function within the function itself, passing in the modified parameters.

Comment if you have any doubts or suggestions on this Js function 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 *