How to Loop the Javascript Iterator That Comes from Generator?

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 );
}
2

1 Answer

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 ]
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.