A generator is a special function that can pause in the middle and continue later. You write it with function* (a star after the word function) and use the keyword yield to hand out one value and pause.
Calling a generator function does not run its code. It gives you a generator object. Every time you ask this object for the next value, the code runs until the next yield, then waits again. Because it only works when asked, a generator can describe very long, or even endless, lists of values without building them all in memory.
yield pauses and hands out a value. next() resumes. The generator remembers its variables between pauses.
Syntax
JavaScript Syntax
Write a generator, then read its values with next(), for...of and the spread operator:
JavaScript
function* greetings() { // the star makes it a generator
yield "Hello"; // pause and give "Hello"
yield "Hola";
yield "Bonjour";
}
const gen = greetings(); // nothing runs yet
console.log(gen.next()); // { value: "Hello", done: false }
console.log(gen.next().value); // "Hola"
for (const word of greetings()) { // for...of calls next() for you
console.log(word);
}
console.log([...greetings()]); // ["Hello", "Hola", "Bonjour"]
Reference
Core Ideas
Ideas every Generator tutorial in this series builds on:
Idea
Example
Remember
function*
function* numbers() { ... }
Declares a generator function
Generator object
const gen = numbers();
What calling a generator function gives back; it has next(), return() and throw()
yield
yield 5;
Pauses the generator and hands out a value
next()
gen.next()
Resumes the generator and returns { value, done }
done
result.done
false while more values may come, true when finished
yield*
yield* otherGenerator();
Hands out all values of another generator or list
Iterable
for (const x of gen)
A generator works with for...of, spread and Array.from()
Lazy
while (true) { yield n++; }
Values are made only when asked for
Compare
Generator Function vs Regular Function
A generator function looks like a normal function, but it behaves differently:
Feature
Regular function
Generator function
Written with
function name() { }
function* name() { }
What a call does
Runs the whole body
Only creates a generator object
Values it gives
One, with return
Many, one for each yield
Can pause
No
Yes, at every yield
Remembers variables between calls
No, each call starts fresh
Yes, until it finishes
An arrow function cannot be a generator, but a method in an object or a class can: write *name() { }.
Behavior
How Generators Work
Calling does not run the code
Writing const gen = countdown(3) only creates the generator object. The code inside starts running at the first next().
yield pauses, next() resumes
Each next() runs the code until it reaches a yield. The value after yield goes out, and the generator waits. The next next() continues on the next line.
The result is { value, done }
While the generator has more to give, done is false. When the code ends (or reaches return), done becomes true, and all further calls give { value: undefined, done: true }.
Loops call next() for you
for...of, the spread operator [...gen] and Array.from(gen) keep calling next() until done is true. Example 1 shows all three.
You can stop or interrupt it
return() ends a generator early and lets finally clean up. throw() sends an error into the paused generator. A generator is used once: to start again, call the generator function again.
Practice
Real-Life Uses
Generators are not needed every day, but they are very handy when values come one at a time:
Use
What it does
Endless or very long lists
Produce IDs, numbers or pages of data one at a time, without building a huge array.
Custom loops
Make your own object work with for...of by writing *[Symbol.iterator]().
Reading data step by step
Process a large file or a list of records line by line, and stop whenever you have enough.
Step-by-step tasks
Describe a process that pauses between steps, for example a wizard or an animation.
Code
JavaScript Examples
Three short programs. Each one prints plain text, so the output is the same in Node.js and in the browser console.
Example 1 — Write Your First Generator
A countdown generator, read in three different ways.
JavaScript
function* countdown(from) {
for (let n = from; n > 0; n--) {
yield n;
}
}
const gen = countdown(3);
console.log(gen.next().value);
console.log(gen.next().value);
for (const n of countdown(3)) {
console.log("for...of: " + n);
}
console.log("Spread: " + [...countdown(3)].join(", "));
console.log("Array.from: " + Array.from(countdown(4)).join(", "));
An endless source.naturals() would count forever, but it only moves when asked, so it does not freeze the program.
Helpers that stop.take(count, source) passes on values and returns after count of them. When it stops, JavaScript calls return() on the source generator for you.
Chain them.map() squares each number. Together, take(4, map(naturals(), ...)) produces 1, 4, 9, 16 and never works out a fifth value.
Continue
Generator Methods
A generator object has three methods. Each one has its own tutorial:
A generator is a function written with function* that can pause at each yield and be resumed later. Calling it returns a generator object. You read values from it with next(), a for...of loop, the spread operator or Array.from().
yield pauses the generator and hands one value to the caller. When the caller asks for the next value, the generator continues on the line after the yield, with all its variables still in place.
yield pauses and gives a value, and the generator can go on later. return ends the generator and gives a final value with done: true. Loops such as for...of use the yielded values and ignore the returned one.
An array holds all its values in memory at once. A generator makes each value only when it is asked for, so it can represent huge or endless sequences, and you can stop reading whenever you have enough.
No. When a generator is finished, it stays finished and next() keeps returning { value: undefined, done: true }. To start over, call the generator function again to create a fresh generator object.