Problem with function Undefined return

Asked

Viewed 16 times

-1

Good evening, I made the following algorithm in Javascript:

var res = 1;
console.log(fatorial(3));

function fatorial(n){
    if(n == 1){
        console.log(res);
        return(res);
    }else{
        res *= n;
        fatorial(n - 1);
    }
}

In the console.log(res) the result appears correctly, while in console.log(factorial(3)) message appears Undefined. Someone could explain to me the reason for this and how to make the result appear in both?

Thanks in advance for your attention.

1 answer

0


Missing to return the factorial in your else:

else{
    res *= n;
    return fatorial(n - 1);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.