How to Use for...of Loop with Generators in JavaScript
Use the
for...of loop to iterate over values yielded by a generator function in JavaScript. The generator produces values one by one, and for...of automatically handles the iteration until the generator is done.Syntax
The for...of loop works with any iterable, including generators. The syntax is:
for (const value of generatorFunction()) {
// use value
}Here, generatorFunction() returns a generator object. The loop assigns each yielded value to value until the generator finishes.
javascript
function* generatorFunction() { yield 1; yield 2; yield 3; } for (const value of generatorFunction()) { console.log(value); }
Output
1
2
3
Example
This example shows a generator that yields numbers from 1 to 5. The for...of loop prints each number as it is generated.
javascript
function* countToFive() { for (let i = 1; i <= 5; i++) { yield i; } } for (const num of countToFive()) { console.log(num); }
Output
1
2
3
4
5
Common Pitfalls
One common mistake is trying to use for...of on a generator function itself instead of its returned generator object. You must call the generator function to get the iterable.
Wrong:
for (const val of generatorFunction) { // Missing ()
console.log(val);
}Right:
for (const val of generatorFunction()) {
console.log(val);
}Quick Reference
- Generator function: Declared with
function*and usesyieldto produce values. - for...of loop: Iterates over the generator's yielded values automatically.
- Call the generator: Always use
generatorFunction()to get the iterable.
Key Takeaways
Use for...of with the generator object returned by calling the generator function.
Generators yield values one at a time, and for...of loops through them until done.
Never forget the parentheses when calling the generator function inside for...of.
for...of simplifies consuming generator values without manual iteration control.