Search code examples
javascriptfactorial

JavaScript factorial


Cant wrap my head around arguments.callee and why truefactorial = 120. Some help would be much appreciated

    function factorial(num){
        if (num <= 1) {
            return 1;
        } else {
            return num * arguments.callee(num-1)
        }
    }

    var trueFactorial = factorial;

    factorial = function(){
        return 0;
    };

    alert(trueFactorial(5));   //120

Solution

  • Inside a function, arguments.callee refers to that function.

    So factorial is recursive - it calls itself. No matter what name you might use for it.

    Redefining the name factorial to reference a different function has no affect on the first definition, because nowhere in that first definition does it use the name factorial.