I do not understand why this result gives me, someone would explain to me a little the why of this result please?
function a(n){
if (n === 0) {
return 1;
} else {
return a(n - 1) * n;
}
}
console.log(a(8)); // => 4320
I do not understand why this result gives me, someone would explain to me a little the why of this result please?
function a(n){
if (n === 0) {
return 1;
} else {
return a(n - 1) * n;
}
}
console.log(a(8)); // => 4320
Your function is known as recursion in Javascript. And it serves to calculate the factorial of a given number.
In the case of the example, the factorial of 8
would be 40320
.
If you pass the number 9
for example, it would result in 362880
.
The recursion in Javascript is explained for example in:
And what happens in your code is explained in more detail in this SO question in English:
This function is more perfect, because it handles, for example, negative numbers and zero:
function factorial(num)
{
// Si el número es menor que 0, lo rechaza
if (num < 0) {
return -1;
}
// Si el número es 0, su factorial es 1
else if (num == 0) {
return 1;
}
// En caso contrario, llama la función recursiva otra vez
else {
return (num * factorial(num - 1));
}
}
var result = factorial(8);
console.log(result);
var result = factorial(-8);
console.log(result);
var result = factorial(0);
console.log(result);
var result = factorial(9);
console.log(result);