The Yield Keyword
You'll learn how yield pauses a generator function and hands back a value, then picks up right where it left off.
What Does Yield Do?
The yield keyword is the magic that makes generators special. When a generator function hits a yield statement, it pauses execution at that exact spot, returns a value to the caller, and waits. The next time you call .next() on the generator, it resumes from the line right after that yield.
Think of it like a bookmark in a recipe. You follow steps until you see "pause here," you deliver what you've made so far, and when someone says "continue," you pick up from the next instruction—not from the beginning.
How It Works
function* simpleGenerator() {
console.log('Start');
yield 1;
console.log('Middle');
yield 2;
console.log('End');
}
const gen = simpleGenerator();
gen.next(); // Logs "Start", returns { value: 1, done: false }
gen.next(); // Logs "Middle", returns { value: 2, done: false }
gen.next(); // Logs "End", returns { value: undefined, done: true }
Notice how execution stops at each yield and the value after yield becomes the value property in the result object. The function doesn't restart from the top—it remembers exactly where it paused.
Why This Matters
Without yield, a function runs to completion in one go. With yield, you get lazy evaluation—values are produced only when requested. This is perfect for sequences, streams, or any situation where you want to generate values on demand rather than all at once.
Key Takeaway: yield pauses a generator function, returns a value, and bookmarks the exact spot to resume from on the next .next() call.