DEV Community

Cover image for What is Recursion in JavaScript
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

What is Recursion in JavaScript

Recursion is a powerful programming technique where a function calls itself to solve a problem. This approach is useful for issues broken down into smaller, similar subproblems.

  1. Base Condition
  2. Function Call
  3. Argument of Subsequent Function calls

1. Base Condition: A condition that stops the recursive calls. Without it, the function calls will continue indefinitely. Typically set using an if-else block.

2. Function Call: Knowing where to place recursive calls is crucial. Incorrect placement can either break recursion or cause an infinite loop.

3. Arguments for Subsequent Calls: Ensure that the arguments change in a way that the base condition will eventually be met. Incorrect arguments can prevent the base condition from being satisfied, leading to infinite recursion.

1. Example:

  function Demo(x) {
        console.log(x);
        if (x < 10) {
          Demo(++x);
        }
  }
      let data = 0;
      Demo(data);
Enter fullscreen mode Exit fullscreen mode

Output:

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10
Enter fullscreen mode Exit fullscreen mode

How to Find Mathematical Factorial ?

if you want to find 5 Factorial in mathematics, We have find 5 , 4 , 3 factorial in mathematics.

Example:

5 = 5 * 4 * 3 * 2 * 1 = 120
4 = 4 * 3 * 2 * 1 = 24
3 = 3 * 2 * 1 = 6

** 2.Example:**

How to Find 5 Factorial by using Recursion?


function Fact(item) {
        console.log("Function Call - ",item);

        if (item == 0) {
          return 1;
        }
        return item * Fact(item - 1);
}
      let Num = 5;
      console.log(" >> 5 Factorial is: ",Fact(Num));
Enter fullscreen mode Exit fullscreen mode

output:

Function Call -  5 
Function Call -  4 
Function Call -  3 
Function Call -  2 
Function Call -  1 
Function Call -  0
>> 5 Factorial is: 120
Enter fullscreen mode Exit fullscreen mode

Top comments (0)