---
# System prepended metadata

title: What is recursion in JavaScript? - Scaler Topics

---

---
canonical_url: https://www.scaler.com/topics/recursion-in-javascript
title: What is recursion in JavaScript? - Scaler Topics
description: In this tutorial, you will learn about recursion in JavaScript with the help of examples. Recursion is a process of calling itself. A function that calls itself is called a recursive function.
category: Javascript
author: Vishwas Sharma
---

:::section{.main}

Recursion in JavaScript involves a function calling itself, repeatedly executing until it reaches a base case, akin to a loop. It's a powerful technique for solving problems where solutions depend on smaller versions of the same problem. For instance, in the Fibonacci sequence, each number is the sum of the two preceding ones, defined recursively as F(i) = F(i-1) + F(i-2).
:::

:::section{.main}
## Syntax for Recursion in JavaScript

Consider Below the syntax of the recursive function in JavaScript:

```javascript
function recursion() {
    if (condition) {       //desired command
        return;            // return from the current loop
    }
    // Function code
    // recursive step codes
}
recursion();
// This syntax is the easiest and the simplest format a recursive function can take
``` 
We used recursion() as the recursive function in the above example. In this case, the recursive function is **`recursion()`** . In the function, it makes a call to itself until the base condition is met and it stops executing. The second recursion function that occurs outside of the function code takes arguments and only calls the recursive function once.
:::

:::section{.main}
## The Three Parts of a Recursive Function

The recursion in JavaScript works the same as in any other language. Let's analyze the syntax structure shown in the recursion function earlier. While writing a **`recursive function()`**, you must have the following three basic components of that syntax:

1. The Function Declaration.
2. The Base Case.
3. The Recursive Call command.

Let’s understand these three fundamental components.

### 1. The function Definition

This is where the intended recursive function is declared. The process is similar to how a new function is normally declared in JavaScript.

```javascript
function recursion() {     //The declared function takes arguments
    // Function and recursive step codes
}
```

### 2.The Base Condition


The base case is the most critical component of each recursive function. When the problem is divided into smaller jobs, it is the smallest component of the problem to be solved. It can also be seen as the command that, if the set condition is true, it can end the recursion process. 

```javascript 
function recursion() {    // The Function Declaration
    if (true) {           // here is the base case command
        return;
    }
    // Function and recursive step codes
}
```

### 3. The Recursive Call


The Recursive Call command in recursion is only responsible for **`triggering a new recursive call`**. The Recursive Call command is the actual command that addresses the main problem that you want to solve.

```javascript 
function recursion() {    // The Function Declaration
    if (true) {           // The base case
        return;
    }
    // Function code 
    // and recursive step codes
    return ... ;
}
//Here is The Recursive Call command
recursion()
```
:::

:::section{.main}

## Using if...else statement to prevent infinite recursion
To prevent infinite recursion in javascript, you can incorporate an if...else statement within the recursive function to establish a base case where the function stops calling itself. This base case serves as a condition that halts the recursive calls, ensuring the termination of the recursion. For example, in a recursive function calculating factorial:

```javascript

function factorial(n) {
    // Base case: if n is 0 or 1, return 1
    if (n === 0 || n === 1) {
        return 1;
    } else {
        // Recursive case: call the factorial function with n-1 until the base case is reached
        return n * factorial(n - 1);
    }
}
```

In this implementation, the base case checks if the input 'n' is equal to 0 or 1, in which case the function returns 1, halting further recursive calls. Otherwise, the function calls itself with 'n-1' until the base case is met.
:::

:::section{.main}

## How do you define a recursive function?

Defining a recursive function involves writing a function that calls itself within its code. To create a recursive function in JavaScript, follow these steps:

**Define the base case(s):** Identify the condition(s) under which the function should stop calling itself and return a specific value. This prevents infinite recursion.

**Write the recursive case:** Define the logic for calling the function recursively, typically with modified arguments or conditions, moving closer to the base case(s) with each recursive call.
:::

:::section{.main}

## What is a base condition, and Why do you need It?
A base condition, also known as a base case or termination condition, is a critical aspect of recursion. It is the stopping criterion for recursive functions, preventing infinite recursion and ensuring termination. Base conditions define scenarios where the function should stop calling itself and return a result, effectively breaking the recursive chain. Recursive functions would endlessly call themselves without base conditions, leading to stack overflow errors and incorrect results.
:::


:::section{.main}
## Recursion vs Loops

Recursion and loops are control flow mechanisms used in programming but with distinct characteristics.

recursion in javascript involves a function calling itself, repeatedly executing until a base case is reached. It's elegant for solving problems where solutions depend on smaller versions of the same problem. Conversely, loops iterate over a block of code until a condition is met, providing a more straightforward approach for repetitive tasks. While recursion can be more concise and expressive for specific problems, loops are often more efficient in performance and memory usage. Choosing between them depends on the specific requirements and constraints of the problem.
:::


:::section{.main}
## Examples of a recursive function

Consider the examples below to better understand how recursion in javascript works.


### Print Numbers


```javascript
// program to find the sum of natural numbers using recursion

function printNumber(num) {
    console.log(num);
    
    if(nums>1)
     printNumber(num-1);
 }

// take input from the user
const number = parseInt(prompt('Enter a positive integer: '));

// calling the recursive function
printNumber(number);


```
**Output**

```plaintext
Enter a positive integer: 5
5
4
3
2
1
```
**Explanation:**
* If the input number is strictly **`greater than 1`**, the recursive function calls itself again by reducing the value by **`1`**.
* it will print the number in descending order; in a similar way, we can print the numbers in an ascending way.


###  Find Factorial


```javascript
// program to find the factorial of a number
function factorial(x) {

    // if the number is 0
    if (x === 0) {
        return 1;
    }

    //If the number is positive
    else {
        return x * factorial(x - 1);
    }
}

const num = 5;

// calling factorial() if num is non-negative
if (num > 0) {
    let result = factorial(num);
    console.log(`The factorial of ${num} is ${result}`);
}
```

**Output**
```plaintext
The factorial of 5 is 120
```
**Explanation:**
* Function factorial() will recursively call itself by decreasing the number when you call it with a positive integer. This cycle is repeated until the number becomes 1.




:::


:::section{.main}

## Computing Factorial Using Recursion
To compute the factorial of a number using recursion in Python, you can define a function that calls itself until it reaches the base case where the factorial of 0 or 1 is 1. In the above section, we have seen how to compute the factorial of a number in a recursive way. Now, let's see the process of computing the factorial.


[image reference for showing the process](https://www.programiz.com/javascript/recursion)

The above image illustrates the recursive function's iterative process, depicting how each function call invokes itself until reaching the base case, visually capturing the execution flow.

:::


:::section{.summary}



## Conclusion

* A function that calls itself is recursion until it doesn’t (**`Base case`**).
* The `base case` is the smallest condition of the initial problem to be solved.
* Recursion in javascript is a technique for solving problems when the result depends on solutions to the **`lesser versions of the same problem`**.
* Recursion uses functions that call themselves from within their code to solve such **`recursive problems`**.
* there must be a condition for a recursive function to stop calling itself. Otherwise, the function gets invoked and called **`infinitely`**.
* We have discussed in detail how recursion in javascript works with the help of **`various examples`**.

:::