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

Stateful Iterators

Understand how iterators maintain internal state across multiple next() calls.

What You'll Learn

You'll learn how iterators keep track of where they are in a sequence using internal state that persists between next() calls.

Understanding Stateful Iterators

When you call next() on an iterator, it needs to remember where it left off so the next call knows what to return. This is internal state — data the iterator stores to track its progress through a sequence.

Think of it like reading a book with a bookmark. Each time you stop reading (call next()), you place the bookmark on your current page. When you return later, the bookmark tells you exactly where to resume. Without that bookmark, you'd have no idea where you were!

How State Works in Practice

When you create an iterator, it typically initializes some state (like a counter or position). Each next() call:

  1. Reads the current state
  2. Produces a value based on that state
  3. Updates the state for the next call
  4. Returns the result
const rangeIterator = {
  current: 0,  // State: current position
  end: 3,
  
  [Symbol.iterator]() {
    return this;
  },
  
  next() {
    if (this.current < this.end) {
      return { value: this.current++, done: false };  // Updates state
    }
    return { done: true };
  }
};

console.log(rangeIterator.next().value);  // 0 (state now 1)
console.log(rangeIterator.next().value);  // 1 (state now 2)
console.log(rangeIterator.next().value);  // 2 (state now 3)
console.log(rangeIterator.next().done);   // true

Notice how current starts at 0 and increments with each call. The iterator "remembers" its position automatically.

Key Takeaway: Stateful iterators maintain internal variables that track their position or progress, allowing them to produce the correct sequence of values across multiple next() calls without losing their place.