1

I'm trying to run a recursive function that calculates the factorial of a number on an HTML input. I already know how to do it via iteration, I want to achieve the result recursively. But when I do it this way, I get a 'too much recursion' error. What am I missing?

HTML

    <input type="text" name="factorial_input" placeholder="Enter a number">
    <div class="button" onclick="calculateFactorial()">Let's see the factorial</div>

JS

function calculateFactorial(getInputValue) {
getInputValue = document.querySelector("input").value;

if (!getInputValue) {
    console.log("You must enter a number");
} else if (getInputValue == 0) {
    return console.log("1");
} else {
    return console.log(getInputValue *= calculateFactorial(getInputValue - 1));
}

// console.log(getInputValue);

}

2 Answers 2

1

You are having endless recursion issues because you are retrieving the value from input in recursive function and that's why the getInputValue variable gets fresh value every time. It's the wrong implementation you did. Try the example given below.

The HTML

<input type="text" name="factorial_input" placeholder="Enter a number">
<div class="button" onclick="calculateFactorial()">Let's see the factorial</div>

The Script

function calculateFactorial(getInputValue) {
    let getInputValue = parseInt(document.querySelector("input").value);
    console.log(fact(getInputValue));
}

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

The recursive function needs a satisfactory condition to return from recusrion to return the call stack. Otherwise, It'll go to the endless call.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thank you! I didn't think of using a function call within another function. Very helpful
0

Why are you having getInputValue as the function parameter if you are not passing it to the function anyway?

Don't mix things together, it only makes things harder to understand.

Instead make a factorial function that only calculates factorial value, pass input's value to the function then console.log() it out.

function factorial(number) {
  return number == 1 || number == 0 ? number : number * factorial(number - 1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.