Please spot the mistake in the code. I don’t know how to do recursion by removing parameters. When I remove parameters, code begins to work fine.
Code Snippet
let number = document.getElementById("inputN").value;
function result2(number) {
if (number == 1)
return 0;
if (number == 2)
return 1;
let answer;
answer = (number - 1) * (result2(number - 1) + result2(number - 2));
return answer
document.getElementById("result").innerHTML = "Result: " + result2(number);
}
<label for="inputN">Enter the value of n:</label>
<input type="number" id="inputN" min="1" step="1" value="1">
<button onclick="result2(number)">Calculate</button>
<p id="result"></p>
2
Answers
There are a couple of significant problems here:
return
statement, so it can never execute.number
once, and only once, when the page loads. That value is1
. You always call the function with1
, so it always immediately returns.You can correct both of these by separating your concerns into two functions. One which reads the input value and writes the output value, and which calls the other function which performs the calculation (recursively). For example:
Note how the
recurse
function only performs the calculation and returns the result. It is not concerned with where the value came from or what is done with the result.The other function,
getResult
, is what gets invoked by the UI. That function reads the input value, invokes the calculation, and displays the result.There’s a couple issues with the code you’ve provided.
First off the ‘return’ statements like below mean nothing else will be executed
Second, you set ‘number’ once at the page load. Instead we should just retrieve this number each time the function is called and forget about parsing it in.
This means refactoring the below to something like this, with an ‘internal calculate’ to obtain your return ‘0’ or ‘1’ functionality.
But also, what happens if you don’t have a ‘1’ or ‘0’ – we should return a default. In this case I just made it 0. Full snippet is below, extracting your internal functionality.