0

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.

2
  • 3
    what about the else branch of your code, where n <= 1? try else return 1 :D Commented Mar 10, 2021 at 6:06
  • 3
    You have no return for else case. That's why it is by default returning undefined for "else" and undefined + a number = NaN. Commented Mar 10, 2021 at 6:06

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

can you please point me to a video that teaches me how to trace code please?
@JeffKyei Well sorry, I don't know if there are such videos. But I'll try to explain in text. Firstly, lets define myFunc(n) as f(n) for shorter naming. Let the tracing begin in computation order. f(4) = 4 * f(3), And then, because function rank is higher than multiplication, it will try compute the f(3) first. = 4 * 3 * f(2) = 4 * 3 * 2 * f(1) = 4 * 3 * 2 * 1 = 12 * 2 * 1 = 24 * 1 = 24 Notice f(1) returns 1 because we define the implicit case to return 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.