Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for..of and the iterator state

Consider this python code

it = iter([1, 2, 3, 4, 5])

for x in it:
    print x
    if x == 3:
        break

print '---'

for x in it:
    print x

it prints 1 2 3 --- 4 5, because the iterator it remembers its state across the loops. When I do seemingly the same thing in JS, all I get is 1 2 3 ---.

function* iter(a) {
    yield* a;
}

it = iter([1, 2, 3, 4, 5])

for (let x of it) {
    console.log(x)
    if (x === 3)
        break
}

console.log('---')

for (let x of it) {
    console.log(x)
}

What am I missing?

like image 569
georg Avatar asked Mar 26 '18 13:03

georg


People also ask

What is for of and for in loop?

for...of Vs for...inThe for...in loop is used to iterate through the keys of an object. The for...of loop cannot be used to iterate over an object. You can use for...in to iterate over an iterable such arrays and strings but you should avoid using for...in for iterables. The for...of loop was introduced in ES6.

What's the difference between Forin and for of?

The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object.

Does for of iterate in order?

Yes. But hunting it down is a littlebit complicated, as for of doesn't only iterate arrays (like for in does enumerate objects). Instead, it generically iterates all iterable objects - in the order that their respective iterator supplies.

What is the difference between for in and for...of loop in JS?

The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.


1 Answers

Generator objects in JS are not reusable unfortunately. Clearly stated on MDN

Generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword. Upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results.

like image 168
Andrey Avatar answered Sep 19 '22 23:09

Andrey