Search code examples
javascriptiteratorgeneratorecmascript-6

How to loop the JavaScript iterator that comes from generator?


Let's assume that we have following generator:

var gen = function* () {
  for (var i = 0; i < 10; i++ ) {
    yield i;
  }
};

What is the most efficient way to loop through the iterator ? Currently I do it with checking manually if done property is set to true or not:

var item
  , iterator = gen();

while (item = iterator.next(), !item.done) {
  console.log( item.value );
}

Solution

  • The best way to iterate any iterable (an object which supports @@iterator), is to use for..of, like this

    'use strict';
    
    function * gen() {
        for (var i = 0; i < 10; i++) {
            yield i;
        }
    }
    
    for (let value of gen()) {
        console.log(value);
    }
    

    Or, if you want an Array out of it, then you can use Array.from, like this

    console.log(Array.from(gen());
    // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]