Function returns undefined despite the variable having a value

104 views Asked by At

Here is the code. You can test it for yourself.

Please explain :)

var factorial = 1;

function factorialize(num) {
  factorial *= num;

   if (num == 1) {
     var result = factorial;

     return result;
   }

   factorialize(num-1);

}

factorialize(5);
2

There are 2 answers

2
Nina Scholz On BEST ANSWER

It needs no global variable and no local variable, too.

function factorialize(num) {
    if (num === 1) {
        return 1;
    }
    return num * factorialize(num - 1);
}

console.log(factorialize(5));

// or a very short version:
function f(n) { return +!~-n || n * f(n - 1); }

console.log(f(10)); 

1
Yeldar Kurmangaliyev On

You don't need some variables if you use recursion. That's one of the most interesting things about recursion.

Take a look at this much shorter recursive solution:

function factorial(n)
{
    return (n === 1) ? 1 : n * factorial(n - 1);
}

for (var i = 1; i <= 7; i++)
    document.getElementById("myDiv").innerHTML += (i + "! = " + factorial(i) + "<br/>");
<div id="myDiv">
</div>