
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: 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);
Output:
0 1 2 3 4 5 6 7 8 9 10
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));
output:
Function Call - 5 Function Call - 4 Function Call - 3 Function Call - 2 Function Call - 1 Function Call - 0 >> 5 Factorial is: 120
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!
What are the levels of mobile user star ratings?
How to restore Bluetooth headset to binaural mode
How to turn off sublime auto-completion
How to use pip installation
How to cancel automatic renewal at Station B
Dynamic link library initialization routine failed
How to read a column in excel in python
resample function usage