Yogesh Chauhan's Blog

Recursion in JavaScript

in JavaScript on April 24, 2021

Recursion is when a function calls itself and the function that does is called a recursive function.

You have to be careful writing the recursive function because if it can overflows the stack calling itself again and again.

Just like this factorial recursive function


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

console.log(factorial(10));
//3628800

Or like this power recursive function


function power(a,b) {
  if (b == 0) {
    return 1;
  } else {
    return a * power(a,b-1);
  }
}

console.log(power(2,4));
//16

Both of those functions above call themselves multiple times till they meet the return condition.

Performance wise, calling a function itself is not always effective since its slower than the regular looping function. It’s completely up to the programmer what they want to go with.

If you’re in a dilemma of choosing between the regular loop or a recursive function, I would suggest to test out both ways before going live and compare the performance.

If the program is not big enough then you might find the recursive choice better depending on your program logic.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
New to  Drupal? Here’s What You Need to KnowDrupalClasses in JavaScript: The BasicsJavaScriptHow to Display Related Posts in WordPress?WordPressHow to add menu to your WordPress theme?WordPressIs there a CSS parent selector?CSSDebugging in WordPress Part 3: SCRIPT_DEBUG and SAVEQUERIESWordPressHow to position an image on top of another image using CSS?CSSSequence generator (range) using JavaScript Array.from()JavaScriptHow to force your website to load securely with an .htaccess file?MiscellaneousHow different is Handling Events in React vs HTML DOM?Reactclip and clip-path properties in CSSCSSIs monitoring an employee’s work on a computer a desirable or undesirable activity?Miscellaneous