skip to Main Content

I’m studying and making exercise of the Fibonacci sequence and I don’t understand where is the "i" value goes to?

function fibonacciGenerator (n) {
    
      var output = [];
  if (n === 1) {
    output = [0];
  }     
  else if (n === 2) {
      output = [0, 1];
  }
  else if (n === 0) {
      output = ["Please put in the number"];
  }
  else {
      output = [0, 1];
      for (var i = 2; i < n; i++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }
      
  }
    return output;  
    
  console.log(output); 
}

So the problem line was this loop

else {
      output = [0, 1];
      for (var i = 2; i < n; i++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }

so the code just understand by itself that output that are next to [0,1,…] is "i" right?
Why can’t i just put this line like this

else {
      output = [0, 1];
      for (var n = 2; n < output.length; n++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }

(BTW It said "Uncaught ReferenceError: i is not defined")

2

Answers


  1. for (var n = 2; n < output.length; n++) {
          output.push(output[output.length - 2] + output[output.length - 1]);
      }
    

    will not work because the for-loop condition depends on the array length’s (n < output.length) and you are modifying the array length’s inside the loop.

    For a for-loop, you should use ‘let’ instead of ‘var’, like this

    for (let i = 2; i < n; i++) {
              output.push(output[output.length - 2] + output[output.length - 1]);
          }
    

    Check this stackoverflow post that explains in detail the difference between var and let

    Login or Signup to reply.
  2. The issue in your code is with the loop condition. You are using the same variable n for both the function parameter and the loop variable. This can lead to unexpected behavior. Additionally, the loop condition n < output.length will never be true because you are pushing elements into the output array, making its length always greater than 2.

    else {
          output = [0, 1];
          for (var n = 2; n < output.length; n++) {
              output.push(output[output.length - 2] + output[output.length - 1]);
          }
    

    use the below code it is correct

    else {
          output = [0, 1];
          for (var i = 2; i < n; i++) {
              output.push(output[output.length - 2] + output[output.length - 1]);
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search