recursive function 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.38
8
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(3, 3) ); // 27
Thank you!
8
0
3.4
5
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!
5
0
Are there any code examples left?
New code examples in category Javascript