geostocker geostocker - 25 days ago 7
Javascript Question

Unexplained undefined value on return

I've got an issue with an undefined value in below code that neither me nor any of my collegues can explain:

function reverseFactorial(num) {
function reverse(altNum, fac){
console.log(altNum + ', ' + fac);
if ((altNum / fac) === 1)
{
console.log(fac.toString() + '!');
return fac.toString() + '!';
}

else {
reverse(altNum / fac, fac + 1);
}
}
var ret = reverse(num, 1);
console.log(ret);
return ret;
}


An example input could be:
reverseFactorial(120)
.

The logs would then show this:


120, 1

120, 2

60, 3

20, 4

5, 5

5!

undefined

Answer

The reverse function doesn't always return a value: the else { case has no return statement.

You probably mean to return reverse(altNum / fac, fac + 1); in the else block.