Skip to content

Generator

In one line

A generator is a function declared with function* that can pause execution with yield and resume later, producing a sequence of values.

In simple words

A generator function (declared with function*) can pause its execution with the yield keyword and resume later. Each time you call next() on the generator object, it runs until the next yield and returns the yielded value.

Generators are a convenient way to create custom iterators. They are lazy — values are produced on demand, not all at once. This makes them useful for large sequences, infinite sequences, or complex iteration patterns.

You can also send values back into a generator by passing an argument to next(value) — the yield expression evaluates to that value. This enables two-way communication between the generator and its consumer.

Example

javascript
function* range(start, end) {
  for (let i = start; i < end; i++) {
    yield i;
  }
}
for (const n of range(1, 4)) {
  console.log(n); // 1, 2, 3
}

The generator yields values 1, 2, 3 lazily. for...of consumes the generator.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary