The yield keyword
Learn to pause a generator and return a value with yield.
The yield keyword
The yield keyword is how you produce a value from inside a generator. When yield runs, the generator pauses; the yielded value is returned to the caller. On the next .next() call, execution resumes where it left off.
function* counter() {
yield 1;
yield 2;
}This generator yields 1 first, then 2. Each yield is a separate pause point.
Multiple yield statements
A generator can have multiple yield statements. They run in order: the first .next() goes to the first yield, the second to the next, and so on. This creates a step-by-step sequence of values.
function* colors() {
yield 'red';
yield 'blue';
}
const c = colors();
c.next(); // { value: 'red', done: false }
c.next(); // { value: 'blue', done: false } Exercise Produce colors in order
Write a generator named colors that yields 'red', 'green', 'blue' in order. Create a generator called it and log the three values with console.log via .next().value.
Show example solution
function* colors() {
yield "red";
yield "green";
yield "blue";
}
const it = colors();
console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value);
Test yourself
-
What does the yield keyword do?
- Pauses the generator and returns a value
- Finishes the generator completely
- Restarts the generator from the beginning
- Deletes the generator
Show answer
Pauses the generator and returns a value — Correct! yield produces a value and pauses execution.
-
Add the second yield expression
function* counter() { yield 1; ____ 2; }Show answer
function* counter() { yield 1; yield 2; } -
Compare yield and return
- yield
- produces a value and pauses
- return
- finishes completely
- yield*
- delegates to another generator