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

Why wont it assign the value of the variables over?

I’m trying to make code to calculate the fibonacci sequence and for some reason it wont assign a variable from outside the for statement. Here is my code:

let out = [];
let number1 = 1;
let number2 = 0;

function fibonacci(num1, num2) {
  for (let i = 1; i < (5) + 1; i++) {
    let num3 = 0;
    num3 = num1 + num2;

    out.push(num3);

    //this is testing outputs
    console.log(`${i} num1 ${num1}`);
    console.log(`${i} num2 ${num2}`);
    console.log(`${i} num3 ${num3}`);
    console.log(`${i} out ${out}`);
    //end testing outputs
    number2 = number1;
    num3 = number1
  }
};
document.getElementById("but").onclick = function run() {
  fibonacci(number1, number2);
  document.getElementById("output").textContent = out;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <label>Fibonacci sequence</label><br>
  <button id='but'>Start</button>
  <div id='output'></div>

  <script src="script.js"></script>
</body>

</html>

I tried changing the variables and removing the function called variables. At the beginning all it would give me undefined and 0’s in output but now all it gives me are 1’s. Can anyone help me.

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 :

Here is updated JS

let out = [];
let number1 = 1;
let number2 = 0;

function fibonacci(num1, num2) {
  out = []; // Reset the output array
  for (let i = 1; i <= 5; i++) {
    let num3 = num1 + num2;
    out.push(num3);

    // Update num1 and num2 for the next iteration
    num2 = num1;
    num1 = num3;
  }
}

document.getElementById("but").onclick = function run() {
  fibonacci(number1, number2);
  document.getElementById("output").textContent = out.join(', ');
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <label>Fibonacci sequence</label><br>
  <button id='but'>Start</button>
  <div id='output'></div>

  <script src="script.js"></script>
</body>

</html>
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