Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do recursion in javascript by taking parameters as input

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are a couple of significant problems here:

  1. The line of code which produces output is after a return statement, so it can never execute.
  2. You define the value of number once, and only once, when the page loads. That value is 1. You always call the function with 1, 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:

function getResult() {
  let number = document.getElementById("inputN").value;
  document.getElementById("result").innerHTML = "Result: " + recurse(number);
}

function recurse(val) {
  if (val == 1)
    return 0;
  if (val == 2)
    return 1;
  return (val - 1) * (recurse(val - 1) + recurse(val - 2))
}
<label for="inputN">Enter the value of n:</label>
<input type="number" id="inputN" min="1" step="1" value="1">
<button onclick="getResult()">Calculate</button>
<p id="result"></p>

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading