dots Created with Sketch.
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 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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
What is Host Hardening and What are some Important Hardening Steps?MiscellaneousWindow innerHeight and innerWidth properties in JavaScriptJavaScriptFunction Scope in JavaScript for BeginnersJavaScript$this Keyword in PHPPHPHow to add new elements with swing animation using JavaScript and CSS?CSSIs there a CSS parent selector?CSSWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?MiscellaneousImplicit and Explicit Joins in Oracle SQLSQL/MySQLSelect statement in Postgres with examplesPostgresIntroduction to components and templates Part 2: Templates and viewsAngularWordPress: How to display fields from ACF Flexible Contents?WordPressLearn to make a responsive gallery using CSS Grid and without media queriesCSS