I have been some time coding, not to much as you will see (1-2 years), but I am facing this question and I am feeling ashamed. This is not the first time I am confused about it. I have looked in some books of other languages as Java, but I can't solve it by myself.
Why in this script the return is undefined?
const factorial = n => {
let result = 1;
const rec = (n) => {
if(n>0) {
result = result * n;
rec(n-1);
} else {
console.log(result)
return result;
}
}
return rec(n);
};
console.log(factorial(5))
120
undefined
PS: I edited to clear what I would like to understand. Why function rec is not returning result?
CodePudding user response:
Your function has multiple calls. Either return from all of them, or none of them.
const factorial = n => {
if(n>0) {
return factorial(n-1) * n;
} else {
return 1;
}
};
const factorial = n => {
let result = 1;
const rec = (n) => {
if(n>0) {
result = result * n;
rec(n-1);
}
}
rec(n);
return result;
};
The alternative is to loop, not recurse
const factorial = n => {
let result = 1;
for (; n>0; n--) {
result = result * n;
}
return result;
};