Summary - Generators
Build a function that generates an infinite number sequence using a generator.
Summary - Generators
In this group you learned the building blocks of generators. You start with function*, produce values with yield, and step through with .next(). You delegate to another generator with yield*, and write async generators with async function*.
Generators provide lazy evaluation: values are produced only when requested. This makes them ideal for infinite sequences and large data streams.
Exercise Write an infinite number sequence
Write a generator named naturalNumbers that produces natural numbers from 1, infinitely. Inside, use a while (true) loop, a let n = 1 counter, and a yield n; increment n each step. Create a generator object called nums and log the first three values via .next().value with console.log.
Show example solution
function* naturalNumbers() {
let n = 1;
while (true) {
yield n;
n++;
}
}
const nums = naturalNumbers();
console.log(nums.next().value);
console.log(nums.next().value);
console.log(nums.next().value);
When to use generators
When should you use generators? They are ideal for infinite sequences: a generator with while (true) can produce endless values without consuming memory. Each value is computed only when .next() is called.
They are also useful for data streams and async iteration. When you want to process a large list in chunks without loading it all into memory, generators are a natural solution.
Exercise Write an ID maker generator
Write a generator named prefix that yields the string 'user'. Write a generator named idMaker that takes a start parameter, first delegates to prefix with yield* prefix(), then yields numbers from start in a while (true) loop. Create a generator called ids and log the first three values via .next().value with console.log.
Show example solution
function* prefix() {
yield "user";
}
function* idMaker(start) {
yield* prefix();
let id = start;
while (true) {
yield id;
id++;
}
}
const ids = idMaker(1);
console.log(ids.next().value);
console.log(ids.next().value);
console.log(ids.next().value);
Test yourself
-
What happens if you use 'while (true)' inside a generator?
- It throws an error
- Memory overflows
- An infinite sequence of values is produced
- The generator never runs
Show answer
An infinite sequence of values is produced — Correct! You can write an infinite generator with while(true); values are produced only as .next() is called.
-
Review generator concepts
- function*
- defines a generator
- yield
- pauses and gives value
- yield*
- calls another generator
- async function*
- async generator