The iterator protocol
An iterator is any object with a next method that returns an object holding a value and a done flag. An iterable has a special iterator method that produces one. This protocol powers for of loops, spread, and destructuring.
- next advances the sequence and reports when it is done.
- done becomes true when there is nothing left.
- Arrays, strings, maps, and sets are all iterable.
Generators that pause
A generator function, written with a star, builds an iterator for you. Each yield pauses execution and hands a value to the caller, resuming where it left off on the next call.
- Generators can produce infinite sequences lazily.
- The caller can send a value back into the function through next.
- They make custom iterables short and readable.
Because generators compute values on demand, they avoid building large arrays up front. This laziness is their main advantage, letting you model streams and ranges that would be wasteful to materialize fully.
Key idea
The iterator protocol standardizes stepping through values, and generators implement it by pausing at each yield and resuming on demand.