Nick Solonko Nick Solonko - 6 months ago 17
Javascript Question

Why do I get NaN when I call this factorial function?

This is a function to find the factorial. The issue appeared when I added the typeof line. Here is the code:

function factorial(num) {
if ((typeof num) == "number") {
if (num < 0) {
error.innerHTML = "Choose a positive number or 0!";
}
else if (num == 1 || num == 0) {
return 1;
}
else {
return num * factorial(num - 1);
}
}
}


Whenever it's called, I do not get a number as an answer and instead get "NaN".

I am trying to calculate permutation with this code:

Math.floor(factorial(n)/factorial(n-r));


It does work with normal factorial, but not with that equation.

Answer

You are probably passing a string into your factorial function. This can happen if n is set via user input.

factorial("9") / factorial("4") returns NaN.

To convert a string to a number, use +:

var n = +myInput.value;
var r = +myOtherInput.value;
console.log( Math.floor(factorial(n) / factorial(n-r)) );