JavaScript › Iterators & Generators

How do you write a basic generator function?

Beginner

Answer

Add an asterisk after 'function' to make it a generator; calling it doesn't run the body immediately but returns an iterator, and each yield pauses execution, resuming from that point on the next next() call.
function* countTo3() {
  yield 1;
  yield 2;
  yield 3;
}
const gen = countTo3();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
Real-world example Lazily generating a sequence of values one at a time instead of computing and storing them all upfront.

Common follow-ups: What does gen.next() return once the generator is finished?