Course contentsShow
← JavaScript
Lesson 1109 of 2,72325. Iterators and GeneratorsFree lesson

The yield Keyword: Pausing and Resuming

Learn how yield pauses generator execution and returns a value to the caller.

The yield Keyword: Pausing and Resuming

You'll learn how yield acts as a pause button that stops generator execution and hands control back to the caller.

What Does yield Really Do?

When JavaScript encounters yield inside a generator function, it doesn't just return a value—it pauses the entire function execution right at that spot. The function's state (variables, position in code) is frozen in time. Control returns to whoever called next(), along with the yielded value.

When next() is called again, the generator resumes exactly where it left off, right after the yield statement, as if it had never stopped.

Think of It Like a Video Player

Imagine a generator function as a video:

  • yield is the pause button that stops playback and shows you the current frame
  • Calling next() is hitting play to resume from that exact moment
  • The video player "remembers" where it paused, so you never lose your place

How Pausing Works in Practice

function* simpleGenerator() {
  console.log("Starting");
  yield 1; // Pause here, return 1
  console.log("Resumed after first yield");
  yield 2; // Pause here, return 2
  console.log("Resumed after second yield");
  return 3;
}

const gen = simpleGenerator();
gen.next(); // Logs "Starting", returns {value: 1, done: false}
gen.next(); // Logs "Resumed after first yield", returns {value: 2, done: false}
gen.next(); // Logs "Resumed after second yield", returns {value: 3, done: true}

Notice how the function doesn't run all at once—it executes up to each yield, pauses, and waits for the next next() call.

Key Takeaway: yield is a two-way pause mechanism: it stops execution, returns a value to the caller, and bookmarks its position to resume later when next() is called again.