Skip to the workspace
Pebellslearn by building
Iterators and Generators  ›  Lesson

Iterables and the Iterator Protocol

Iterators and Generators 12 min

javascript / Iterables and the Iterator Protocol

Explore each scene at your own pace.

01 · Iterables and the Iterator Protocol

Iterables and the Iterator Protocol

Iterables and the Iterator Protocol

An iterable supplies a Symbol.iterator method that creates an iterator. Each next call returns an object with done and, when applicable, value.

The protocol separates producing the next item from the loop that consumes it.

See the mechanism

Walk through the modelIterables and the Iterator ProtocolAuthored snapshots of the example; use Run below to test the code.
cursorbefore first item
Obtaining an iterator does not itself consume an item.
1 of 3

Follow one example

javascript

The first two results have done false and the next title. The final result has done true; JSON serialization omits its undefined value field. for...of uses this protocol for you. A custom iterable should generally create independent iterators for independent traversals rather than accidentally sharing a single cursor.

Predict, change and check

Predict: If you create a second iterator from titles after one next call, where does the new iterator start?

Test your explanation: Create two iterators and alternate next calls. Compare this with storing one iterator in two variables.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Iterable and iterator are separate roles

An iterable provides a Symbol.iterator method returning an iterator. The iterator's next method returns a result with a value and a done flag. An object with next alone is not automatically suitable for for...of unless it also satisfies the iterable side of the protocol.

Decide whether a custom iterable creates a fresh iterator for every traversal or returns a shared one-shot iterator. Test two traversals and the empty case. A consumer's early exit can call return on an iterator when the protocol provides it, so cleanup can belong to the iterator rather than to a guessed number of next calls.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.