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

Generator State Preservation

Understanding how generators maintain local variables and execution context between yields.

Generator State Preservation

You'll learn how generators remember their local variables and position between yield statements, making them different from regular functions.

The Core Idea

When a generator function hits a yield, it doesn't just pause—it freezes its entire execution context. All local variables, the current position in the code, and even the call stack are preserved. When you call next() again, the generator resumes exactly where it left off, with all variables intact.

Think of it like pausing a video game: when you press pause, the game saves your character's position, health, inventory, and progress. When you unpause, everything is exactly as you left it.

How It Works in Practice

function* counter() {
  let count = 0;
  while (true) {
    count++;
    yield count;
  }
}

const gen = counter();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Notice how count isn't reset between calls. The generator remembers its value across multiple next() invocations.

Why This Matters

This state preservation is what makes generators powerful for:

  • Maintaining progress through complex sequences
  • Building stateful iterators without external variables
  • Creating lazy evaluation patterns

Unlike calling a regular function multiple times (which resets everything), each next() call continues the generator's internal story from where it paused.

Key Takeaway: Generators preserve their local variables and execution position between yields, maintaining their entire state across multiple next() calls—making them perfect for sequences that need memory.