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);


Or like this power recursive function

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


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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software”MiscellaneousHow SCSS (Sass) finds a module without a file extension?SCSSHow to add MySQL alternate port and sockets/pipes in WordPress?WordPressWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?MiscellaneousAll different methods for accessing elements in the DOM using JavaScriptJavaScriptHow to hide and show menu on scroll using JavaScript and CSS?CSSJavaScript: how to detect a browser using the user agent?JavaScriptHow to create a CSS full page background image?CSSHow to modify the latest post array using get_posts() in WordPress?WordPressINTERSECT and EXCEPT in PostgresPostgresDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressArbitrary Arguments in SCSS functionsSCSS