MartianMartian
MartianMartian

Reputation: 1849

What is wrong with my javascript recursion?

What is wrong with this recursion function? fac(5) gives NaN

function fac(num){
  while(num>2){
    return(num*fac(num-1))
  }
}

Upvotes: 2

Views: 115

Answers (4)

Vigneswaran Marimuthu
Vigneswaran Marimuthu

Reputation: 2532

What's wrong with your code

function fac(num){
  while(num>2){
    return(num*fac(num-1))
  }
}
  • No return value for num <= 2. So, at some point your code will multiply Number with undefined which results in NaN

  • while loop is not needed

function fac(num) {
    return (num > 2) ? num * fac(num - 1) : 1;
}

alert(fac(5));

Upvotes: 1

Akash Yadav
Akash Yadav

Reputation: 2421

NaN - not a number error , occurs usually but not limited to when we try to apply a numerical operation to a value which is not a number.

The Issue at hand is when the input value is less than 2 , the function return undefined, which is not a number, so the return (num*fac(num-1)) will fail due to num * undefined. to fix this , we have to return a value when number is 2 or less than 2.

function fact(num) {
    if(num > 2)
        return num * fact(num - 1);
    else
        return num;
}

Upvotes: 2

deostroll
deostroll

Reputation: 11975

The correct way should be:

function fact(num) {
    if(num > 2)
        return num * fact(num - 1);
    else
        return num;
}

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

fac(1) returns nothing, which is undefined, and undefined*1 is NaN, that's why.

Change your code to

function fac(num){
  return num>2 ? num*fac(num-1) : 1;
}

Upvotes: 4

Related Questions