recursion in javascript
// Basic Recursive function
// It works in all languages but lets try with Javascript
// lets make a greedy factorial calculator
function my_recursive_factorial(nb) // nb to compute his factorial
{
if (nb < 0 || nb > 12) // error case
return 0;
if (nb == 1 || nb == 0)
return 1; // you have to check limit for factorial
return nb * my_recursive_factorial(nb - 1); // ! Recursive call !
}
//This will find factorial from 1 to 12 with recursive method
// Recursive functions are greedy and should be used in only special cases who need it
// or who can handle it.
// a function become recursive if she calls herself in stack
4.5
2
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(3, 3) ); // 27
Thank you!
2
0
4.5
2
/*Java*/
static void recursion(){ recursion(0); }
static void recursion(int x){
System.out.println("eheh " + x);
if(x != 666) recursion(x+1);
}
Thank you!
2
0
4.2
10
function recurse(arr=[])
{
// base case, to break the recursion when the array is empty
if (arr.length === 0) {
return;
}
// destructure the array
const [x, ...y] = arr;
// Do something to x
return recurse(y);
}
Thank you!
10
0
4
2
var countdown = function(value) {
if (value > 0) {
console.log(value);
return countdown(value - 1);
} else {
return value;
}
};
countdown(10);
Thank you!
2
0
Are there any code examples left?
New code examples in category Javascript
-
Javascript 2023-04-21 22:52:36
-
Javascript 2022-03-27 22:25:20 javascript download string as file
-
Javascript 2022-03-27 21:40:22 sort numbers in array javascript
-
Javascript 2022-03-27 21:20:04 compare two arrays and return the difference javascript
-
Javascript 2022-03-27 21:15:02 javascript regex french phone number
-
Javascript 2022-03-27 21:05:03 cypress custom error message
-
Javascript 2022-03-27 21:00:05 create element javascript with id
-
Javascript 2022-03-27 20:40:57 feather icons react
-
Javascript 2022-03-27 20:20:01 how to make graphql request in axios
-
Javascript 2022-03-27 20:15:07 bootstrap validator password and confirm password