Jeff Kyei
Jeff Kyei

Reputation: 33

Recursive Function in Javascript showing NaN

I'm experimenting with recursive functions in javascript which takes a number and outputs the factorial of that number. I decided to go for simplicity and do something like this:

function myFunc(n)
{   
    if(n > 1){
        return (n * myFunc(n - 1));
}

}

console.log(myFunc(4));

yet console.log() keeps outputing NaN. What am I doing wrong please? Everything looks right to me.

Upvotes: 0

Views: 124

Answers (1)

yaputra jordi
yaputra jordi

Reputation: 533

I quess you are trying to implement factorial using recursive function. If you trace your code manually, you'll find that eventually you will call myFunc(1) and it doesn't have any return as your code only return when n > 1. So all you need to do is to add a return for n == 1 (or any possible n value).

function myFunc(n) {   
    if (n > 1) {
        return (n * myFunc(n - 1));
    }

    /* else if (n <= 1) then return 1. 
     * This is commented because if the first condition fails, 
     * it will continue to execute the rest from here.
     */
    return 1;
}

console.log(myFunc(4));  // output 4!, which is equal to 4 * 3 * 2 * 1 = 24

Upvotes: 3

Related Questions