0

I am trying to lear generators but before going into that I want to know how/why this works

function makeIterator(array){
    var nextIndex = 0;    
    return {
       next: function(){
           return nextIndex++
       }
    }
}
var it = makeIterator([1,2,3,4]);

Why is it that it.next() return 1 and another it.next() returns 2. How does it know?

Is there a way to see how it works behind the scenes?

relidon
  • 2,142
  • 4
  • 21
  • 37
  • Note that the first call to `it.next()` results in 0, not 1, and that those numbers are unrelated to the contents of the array you've passed in. – James Thorpe Jul 19 '16 at 10:31
  • 1
    This is related to closures, you should read this post, it's GREAT: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work it changed the way I look at javascript forever. – Dellirium Jul 19 '16 at 10:36

1 Answers1

0

An iterator is an object with state. In your case, the state is the private nextIndex closure variable, that's how it keeps track.

There's no magic going on behind the scenes here, if you didn't have that variable, you'd get an error.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308