Categories
JavaScript Answers

How to call a JavaScript function recursively?

Spread the love

Sometimes, we want to call a JavaScript function recursively.

In this article, we’ll look at how to call a JavaScript function recursively.

How to call a JavaScript function recursively?

To call a JavaScript function recursively, we call the same function inside the function.

For instance, we write

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

to define the factorial recursive function.

In it, we check if n is less than or equal to 1.

If it is, we return 1.

Otherwise, we return n multiplied by the result of factorial called with n - 1.

factorial is called until n is less than or equal to 1.

Conclusion

To call a JavaScript function recursively, we call the same function inside the function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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