Why is the following, simple recursive function outputting ‘undefined’?
var result = 1;
function factorial(x){
if(x == 1){
return result;
}
result *= x;
factorial(x-1);
}
console.log(factorial(5))
Why is the following, simple recursive function outputting ‘undefined’?
var result = 1;
function factorial(x){
if(x == 1){
return result;
}
result *= x;
factorial(x-1);
}
console.log(factorial(5))
Unless your conditional matches, there is no return statement, which returns undefined by default.
Thanks for your help. And why isn’t this outputting the result? Isn’t return 0 supposed to completely kill off the whole function call stack?
var result = 1;
function factorial(x){
if(x == 1){
console.log(result);
return 0;
}
result *= x;
factorial(x-1);
}
Ok, so what I understand is that it is important to have return statement outside the ‘base case’ as well.
You need a return statement outside of the base case, yes.
Also, what you are doing is a sort of ‘faux’ recursion. Recursion should not use global variables.