SyntaxStudy
Sign Up
JavaScript Advanced 5 min read

Generators

Generator Functions

Generator functions use function* and yield to produce sequences lazily, one value at a time.

Example
function* counter(start = 0) {
  while (true) yield start++;
}
const gen = counter(5);
gen.next().value; // 5
gen.next().value; // 6
function* range(s, e, step = 1) {
  for (let i = s; i <= e; i += step) yield i;
}
[...range(1, 10, 2)]; // [1,3,5,7,9]
Pro Tip

Generators are perfect for infinite sequences, pagination, and custom iterators.