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

  1. Define a generator: javascript function* countUpTo(n) { for (let i = 1; i <= n; i++) yield i; }
  2. Iterate with for...of: javascript for (const num of countUpTo(3)) { console.log(num); }
  3. 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");
  4. 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.
  • return in a generator sets the final value and 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.