# One-time iterator operation in JavaScript

Each iterator can participate in the loop only once. This is a bit unexpected, but logical - after all, the passed iterator sets its `done` to `false`, which means it can no longer be iterated over.

Let's make sure of this. Let's have the following generator:

`function *func() { yield 1; yield 2; yield 3; }`

Let's make an iterator:

`let iter = func();`

And iterate over the iterator in one loop:

`for (let elem of iter) { console.log(elem); // 1, 2, 3 }`

And now iterate over the iterator in two loops:

`for (let elem of iter) { console.log(elem); // 1, 2, 3 } for (let elem of iter) { console.log(elem); // doesn't work }`

To solve the problem, you need to create your own iterator for each new loop:

`let iter1 = func(); for (let elem of iter1) { console.log(elem); // 1, 2, 3 } let iter2 = func(); for (let elem of iter2) { console.log(elem); // 1, 2, 3 }`

We can simplify:

`for (let elem of func()) { console.log(elem); // 1, 2, 3 } for (let elem of func()) { console.log(elem); // 1, 2, 3 }`

Fix the error in the following code:

`function *func() { for (let i = 1; i <= 3; i++) { yield i; } } let elems = func(); for (let elem of elems) { console.log(elem); } for (let elem of elems) { console.log(elem); }`
←→
↑
en ru