18

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
    next is a function which return an object iterator.next().value iterator.next().done ..so it should be item().value and item().done Commented Dec 17, 2015 at 11:50
  • If your browser supports for... of, feel free to go ahead and use it. Commented Dec 17, 2015 at 11:51

2 Answers 2

19

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 ]
Sign up to request clarification or add additional context in comments.

7 Comments

@thefourtheye, const value of gen() triggers an error in Firefox 42 (SyntaxError: invalid for/in left-hand side). let value of gen() works.
@FrédéricHamidi Can you please try that in strict mode?
Yup, I did (fiddle). May be a Firefox issue, though.
@FrédéricHamidi The language for your Fiddle is set to Javascript 1.7 :)
@RGraham, that's necessary for let to be recognized. In "plain" JavaScript mode, neither const value of, nor let value of work (but var value of does).
|
9

A self-contained, single-line alternative to the while loop in the question is the for loop. And for the special case of iterating through for pure side effect or depletion, rather than doing something with the results at the end, we avert the issue of binding the next item value, then not using it in a for-of solution:

for (let n = iterator.next(); !n.done; n = iterator.next()) {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.