Search code examples
javascriptfunctionfor-loopif-statementfactorial

What is wrong with my Factorial Function logic?


I'm trying to get a factorial number in the JS console in Chrome.
Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.
Thank you very much for answers <3

var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};

Solution

  • Where you said var newX = x * i;, that declares a new variable. Remove var.
    x * i will return the square of x because lastly i is x.

    function factorial(x) {
        var newX = 1;
        if(x > 0){
            for(var i = 1;i <= x;i++){
                newX = newX * i;
            }
            return newX;
        } else {
            return 1;
        }
    };
    console.log(factorial(5));
    console.log(factorial(4));
    console.log(factorial(0));