JavaScript Generators
A generator is a function that can pause and resume. It pauses at each yield and resumes where it stopped.
Pause at each yield
countUp pauses at each yield. Each call to next resumes it and hands out the next value.
function* countUp() {
yield 1;
yield 2;
yield 3;
}
const counter = countUp();
console.log(counter.next().value);
console.log(counter.next().value);
console.log(counter.next().value);The done flag
Each call to next returns an object with value and done. done is false while values remain, and true when the generator ends.
function* oneStep() {
yield "only";
}
const gen = oneStep();
console.log(JSON.stringify(gen.next()));
console.log(JSON.stringify(gen.next()));Loop over a generator
A for...of loop calls next again and again. It stops when done turns true.
function* colours() {
yield "red";
yield "green";
yield "blue";
}
for (const colour of colours()) {
console.log(colour);
}A generator that never ends
A generator can loop forever, because each value waits for a call to next. The caller decides when to stop asking.
function* naturals() {
let n = 1;
while (true) {
yield n;
n += 1;
}
}
const numbers = naturals();
console.log(numbers.next().value);
console.log(numbers.next().value);
console.log(numbers.next().value);Example
function* fibonacci() {
let a = 0;
let b = 1;
while (true) {
yield a;
const next = a + b;
a = b;
b = next;
}
}
const fib = fibonacci();
const firstFive = [];
for (let i = 0; i < 5; i++) {
firstFive.push(fib.next().value);
}
console.log(JSON.stringify(firstFive));Key points
- Generator: a function marked with function* that can pause at yield
- yield: the keyword that pauses a generator and hands out a value
- Calling a generator function gives back a generator object.
- next: the method that resumes a generator until the next yield
- Each call to next returns an object with value and done.
- A for...of loop runs a generator until done is true.
In this example, fibonacci is a generator that never ends. Each yield hands out the next number in the sequence. The loop takes the first five values and stops.
Note
The body of a generator does not run when the generator is created. It runs only when next is called.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What happens when a generator function is called?