Why is this giving Nan and how to fix it?

function factorial(x) {
    if( x == 0 || x == 1)   {
         console.log('1')
    } else   {
         console.log(x * factorial(x - 1));
    }
}

factorial(5)

You aren’t returning anything. So the value of the function is undefined. X is not 0 or 1, so you’re trying to console.log 5 * undefined, which is not a number. You need to return things from functions, console log is just a helper function so you can see what’s happening at any one time

3 Likes

The function return undefined if you not explicit specified in JavaScript