0

Why does the break terminates the iterator returned by foo? We use break to terminate the loop, but why does it kill the iterator too? Is it just how it is, or am I missing a point?

function* foo(){
      yield 1;
      yield 2;
}

let myIterator = foo()
    
for (let o of myIterator) {
   console.log(o);
   break; // closes iterator, triggers return
}

for(let of of myIterator) {
   console.log(o)
}

Thank you very much in advance!

Uğur Kaya
  • 2,287
  • 3
  • 15
  • 23
  • you miss: `foo()` returns an iterator and outside of the loop it is not known. – Nina Scholz Jun 18 '18 at 09:19
  • It breaks the loop so the iterator is not iterated any further. The `for` controls the iterator, not the other way around. – deceze Jun 18 '18 at 09:33
  • Sorry, I just realized that I did not even asked the question properly. Can you please check now, I updated the question. @NinaScholz I realize that it returns an iterator. But when I break the first for ... of loop, the iterator itself is terminated, and the second for ... of loop does not iterate. This is what I am asking why. Can you please see now? – Uğur Kaya Jun 18 '18 at 09:36
  • now it looks like this: https://stackoverflow.com/questions/47238463/how-do-i-reuse-a-generator-in-es6-javascript-in-for-loops – Nina Scholz Jun 18 '18 at 09:43
  • Yes, I clearly missed the point that it was not about break, but about not being able to use the same generator twice. Thanks a lot @NinaScholz! – Uğur Kaya Jun 18 '18 at 09:50

0 Answers0