Home > Web Front-end > JS Tutorial > body text

What is Recursion in JavaScript

王林
Release: 2024-08-08 00:50:33
Original
1135 people have browsed it

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);
Copy after login

Output:

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10
Copy after login

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));
Copy after login

output:

Function Call -  5 
Function Call -  4 
Function Call -  3 
Function Call -  2 
Function Call -  1 
Function Call -  0
>> 5 Factorial is: 120
Copy after login

The above is the detailed content of What is Recursion in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!