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
before first itemFollow one example
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.