Lets have an iterator and a generator created to working similarly.
What is the reason they behave differently in for of loop if it contains break or return statement?
The generator is finished while the iterator still goes after the end of the loop.
function *createGenerator() {
for ( let i=0; i<5; i++ ) {
yield i;
}
}
function createIterator() {
const arr = [1, 2, 3, 4, 5];
return arr[ Symbol.iterator ]();
}
function runForOfLoopOn( iterable ) {
for ( const item of iterable ) {
if ( item == 2 ) {
break;
}
}
}
const iterator = createIterator();
const generator = createGenerator();
runForOfLoopOn( iterator );
runForOfLoopOn( generator );
console.log( 'Iterator is done:', iterator.next().done );
console.log( 'Generator is done:', generator.next().done );