0Pricing
JavaScript Academy · Lesson

Generator functions, yield, and small pipelines

Write generator functions with function*, use yield to produce values lazily, drive them with for...of or next(), and compose tiny pipelines.

Why generators?

Goal: Produce values lazily with generators.

  • function* defines a generator
  • yield produces values step by step
  • Use for...of or next() to consume
  • Compose tiny pipelines (map-like)
Generator functions, yield, and small pipelines — illustration 1

function* and yield

Generators use function* and yield. Iteration resumes from the last yield.

// A basic generator that yields 1..n lazily
function* countTo(n) {
  for (let i = 1; i <= n; i = i + 1) {
    yield i; // pause here and give i to the caller
  }
}

for (const x of countTo(3)) {
  console.log("value:", x);
}
Generator functions, yield, and small pipelines — illustration 2

All lessons in this course

  1. Iterable protocol and for...of
  2. Generator functions, yield, and small pipelines
  3. Async iterators — for await...of and async generators
← Back to JavaScript Academy