Search code examples
javascriptfactorial

factorial function running error : Maximum call stack size exceeded


I have made a calculator using javascript . I want to add factorial to it but chrome said to me : Maximum call stack size exceeded. these are some parts of code , I am sure the problem is these code not other

function fac(firstNum){
    firstNum=Number(document.getElementById('result').value);
    if(firstNum==0){
        document.getElementById('result').value = 1;
    }
    var a = firstNum*fac(firstNum-1);
    document.getElementById('result').value = a;
}

and using function into switch case

case 'n!':
    document.getElementById('result').value = fac();
break;

what's the problem ?


Solution

  • You need to separate the factorial algorithm from the UI code.

    function factorial(n) {
      if (n == 0) {
        return 1;
      } else {
        return n * factorial(n - 1);
      }
    }
    

    And then use this code to retrieve the number from the UI field, say factInput and place the result field, say factResult:

    var number = document.getElementById('factInput').value;
    document.getElementById('factResult').value = factorial(number);
    

    HTH, Bryan