← Lessons

quiz vs the machine

Gold1430

Frontend

Generators and Iterators

Iterators expose values one at a time, and generators let a function pause and resume.

5 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. What does an iterator next method return?

2. What does the yield keyword do in a generator?

3. Why are generators useful for large sequences?