0

This is the code to do a Fibonacci Generator. I cannot understand what the i++ and y++ are doing and how all this is resulting in giving us the sequence. :(

function fibonacciGenerator(n) {
  var fib = [0, 1];
  var i = 0;
  var y = 1;

  if (n === 1) {
    fib.pop();
  } else {
    for (var i = 0; fib.length < n; i++) {
      fib.push(fib[i] + fib[y]);
      y++;
    }
  }
  return fib;
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • i and y and indexes into `fib` – Jaromanda X Dec 20 '19 at 23:45
  • Consider reading some Javascript learning manual. ++ is an operator and here is a description of what it does - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment – edgars Dec 21 '19 at 00:07
  • Hi there, welcome to StackOverflow! Please consider reading the StackOverflow publishing guide lines: https://stackoverflow.com/help/how-to-ask – Francis Rodrigues Dec 21 '19 at 00:13

1 Answers1

0

i is always fib.length - 2, and y is always fib.length - 1. Every iteration increases the size of the array, so these two counters must be incremented to always point to the last two slots.

Mori Bellamy
  • 151
  • 6