title: How to create a Javascript generator to calculate the Fibonacci sequence?
body: <p>I've put together a generator to calculate the Fibonacci numbers/sequence. However, it's not working as I expect. I've "transpiled" it from python but I don't know what it is in my JavaScript code that doesn't fit my logic as python does... Can anyone give me a hint on this?</p>
  
  <p>Here's the code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// Fibonacci generator
  function* fibonacci() {
    var a = 0;
    var b = 1;
    while (true) {
      yield a;
      a = b;
      b = a + b;
    }
  }
  
  // Instantiates the fibonacci generator
  fib = fibonacci();
  
  // gets first 10 numbers from the Fibonacci generator starting from 0
  for (let i = 0; i &lt; 10; i++) {
    console.log(i + ' =&gt; ' + fib.next().value);
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>I think this is a matter of variable scope. I've just got this to work by doing so:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// Fibonacci generator
  function* fibonacci() {
    var a = 0;
    var b = 1;
    while (true) {
      var current = a;
      a = b;
      b = current + a;
      yield current;
    }
  }
  
  // Instantiates the fibonacci generator
  var fib = fibonacci();
  
  // gets first 10 numbers from the Fibonacci generator starting from 0
  for (let i = 0; i &lt; 10; i++) {
    console.log(i + ' =&gt; ' + fib.next().value);
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>However, I still don't understand why I need to declare a third variable ("current"), within my loop, to obtain the desirable result. Any ideas?</p>
  
  <p>EDIT: You guys are right. The problem is the variables were being assigned in two steps and therefore not getting the desired values. Here's the final, working code, that I decided to post for future reference:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// Fibonacci generator
  function* fibonacci() {
    [a, b] = [0, 1]
    while (true) {
      yield a;
      [a, b] = [b, a + b]
    }
  }
  
  // Instantiates the fibonacci generator
  var fib = fibonacci();
  
  // gets first 10 numbers from the Fibonacci generator starting from 0
  for (let i = 0; i &lt; 10; i++) {
    console.log(fib.next().value);
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Thank you very much!</p>