The yield keyword is used inside generator functions to pause and resume execution, producing a sequence of values on demand.

💡 What is yield?
yield pauses a generator function and returns a value to the caller, resuming from that point when next invoked.
Basic Syntax
A generator function uses function* syntax and yield to output values:
📌 Deep Dive: Simple Generator
function* count() {
yield 1;
yield 2;
yield 3;
}
const iterator = count();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
2
3
Use Cases of yield
- Lazy Iteration: Generate values on demand rather than all at once, saving memory.
- Asynchronous Programming: Pausing execution at
yieldcan simplify async flows (e.g., with libraries beforeasync/await). - Implementing Iterators: Easily create custom iterable objects by yielding sequence values.
- State Machines: Manage complex state transitions by pausing and resuming at each state.
- Infinite Sequences: Generate potentially infinite data streams without blocking or heavy memory use.
💡 Key Insight
Generators with yield allow stepping through data or logic one piece at a time, rather than all at once.
Example: Infinite Sequence Generator
📌 Deep Dive: Infinite Numbers
function* infiniteNumbers() {
let num = 1;
while (true) {
yield num++;
}
}
const gen = infiniteNumbers();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// and so on...
2
3
Comparison: yield vs return
yield | return |
|---|---|
| Pauses function, produces a value, and can resume later | Exits function immediately, producing a single value |
Used inside generator functions (function*) | Used in any function |
| Allows producing multiple values over time | Produces exactly one value |
| Enables lazy iteration | Does not support iteration |
⚠️ Important
Generators must be iterated via their iterator (.next()) or with for...of loops to access yield values.
Common Pattern: Using yield with for...of
📌 Deep Dive: Iterating Generator
function* colors() {
yield 'red';
yield 'green';
yield 'blue';
}
for (const color of colors()) {
console.log(color);
}
green
blue
💡 Summary
yield is a powerful tool to create generators that produce values on demand, enabling efficient iteration, complex state management, and lazy evaluation.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does the yield keyword do inside a generator function?
Question 2 of 2
Which use case is NOT typical for yield?
Loading results...