Hack Frontend Community

What are Generators in JavaScript?

Generators are functions that can pause their execution and resume it later. They give more control over execution flow, unlike regular functions.

Generators are defined using function* and controlled via the .next() method.

Generator Syntax

function* generatorFunction() {
  yield 'First value';
  yield 'Second value';
  return 'Final';
}

const gen = generatorFunction();

console.log(gen.next()); // { value: 'First value', done: false }
console.log(gen.next()); // { value: 'Second value', done: false }
console.log(gen.next()); // { value: 'Final', done: true }

How Generator Works

  • yield — keyword that pauses execution and returns value.
  • .next()resumes execution from the last yield.
  • done: true — indicates generator is finished.

Differences from Regular Functions

FeatureRegular FunctionsGenerators
Returning valuesOnly one returnMany yield
Intermediate statesNoYes
Flow controlNoYes
Using for..ofNoYes

Generators and Iterators

Generator is an iterator that follows the Iterable protocol. This allows using it in for...of loop.

function* range(start, end) {
  for (let i = start; i <= end; i++) {
    yield i;
  }
}

for (const num of range(1, 5)) {
  console.log(num); // 1, 2, 3, 4, 5
}

When to Use Generators?

Useful for:

  • Working with data streams — e.g., generating sequences.
  • Iterable structures — arrays, trees, graphs.
  • Execution control — e.g., when manual step-by-step data processing is needed.
  • Creating lazy evaluations.
  • Simulating async behavior before async/await appeared.