Chapter XXIV · Advanced Concepts

Generators

Generator functions use `function*` and `yield` to pause and resume execution, producing sequences of values lazily.

01 How It Works

Think of an automated vending machine slot dispensing items one at a time only when requested.

Calling a generator returns a generator iterator object. Each `yield` expression suspends execution and returns a value.

example.js
function* countSequence() {
  yield 1;
  yield 2;
  yield 3;
}
const gen = countSequence();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
  1. 1. Declare a generator function using an asterisk (`function*`).

  2. 2. Use the `yield` keyword to pause and emit values.

  3. 3. Iterate using `.next()` or `for...of` loops.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
function* idMaker() {
  let id = 0;
  while(true) yield id++;
}
const gen = idMaker();
console.log(gen.next().value); // 0

Key Takeaway

Generators provide elegant lazy evaluation and pause-resume execution control.

Related Concepts