Search code examples
javascriptruntime-errorfactorial

Factorial of a number in JavaScript throwing RangeError: Maximum call stack size exceeded


I want calculate factorial of a entered number on clicking a button but it throwing a RangeError.

Here is my code it is working without the addEventListener but with addEventListener it is throwing error:

var factInput = parseInt(document.getElementById("fact").value);
var factBtn = document.getElementById("btnFactorial");

factBtn.addEventListener("click", function() {
  document.getElementById("output2").innerHTML = factOfANumber(factInput);
})

function factOfANumber(n) {
  var fact = 0;
  if (n === 1) {
    return n;
  } else {
    fact = n * factOfANumber(n - 1);
  }
  return fact;
}
<div id="FactorialNumber">
  <h1>2. Factorial of a Number</h1>
  <input type="number" id="fact" placeholder="Enter a Number"></input>
  <button id="btnFactorial">Give me Factorial</button>
  <p>Output:</p>
  <p id="output2"></p>
  <hr>

</div>

home.js:13 Uncaught RangeError: Maximum call stack size exceeded
    at factOfANumber (home.js:13)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)
    at factOfANumber (home.js:17)......


Solution

  • This is because when the document is loaded, the value of the input field is blank. When you try reading the value of it and do parseInt() it returns NaN which is Not a Number. So, your solution will be to move it inside the addEventListener() like this:-

    factBtn.addEventListener("click", function(){
        var factInput = parseInt(document.getElementById("fact").value);
        document.getElementById("output2").innerHTML = factOfANumber(factInput);
    });
    

    Here's the entire js code:-

    var factBtn = document.getElementById("btnFactorial");
    factBtn.addEventListener("click", function(){
        var factInput = parseInt(document.getElementById("fact").value);
        document.getElementById("output2").innerHTML = factOfANumber(factInput);
    })
    function factOfANumber(n){
        var fact = 0;
        if(n===1){
            return n;
        }
        return n * factOfANumber(n-1);
    }