How to use generators in JavaScript
· Category: JavaScript
Short answer
Generators are functions declared with function* that can pause and resume execution via yield, producing a sequence of values lazily.
Steps
- Define a generator:
javascript function* countUpTo(n) { for (let i = 1; i <= n; i++) yield i; } - Iterate with
for...of:javascript for (const num of countUpTo(3)) { console.log(num); } - Send values back into the generator:
javascript function* echo() { while (true) { const val = yield; console.log("Echo:", val); } } const gen = echo(); gen.next(); gen.next("hello"); - Use
yield*to delegate to another iterable:javascript function* combined() { yield* [1, 2]; yield* [3, 4]; }
Tips
- Generators are perfect for infinite sequences and streaming data.
returnin a generator sets the finalvalueand finishes iteration.
Common issues
- Calling a generator function returns an iterator object, not the first yielded value.
- Exceptions thrown into a generator with
throw()must be caught inside the generator or they propagate.