Skip to content

Iterators

The iteration protocol defines a standard way to produce a sequence of values. An iterable has a Symbol.iterator method that returns an iterator (an object with a next() method).

  • Understand the iteration protocol (iterable + iterator)
  • Use for...of with built-in iterables
  • Create custom iterables with Symbol.iterator
  • Know which built-in types are iterable
sequenceDiagram
participant Loop as for...of
participant Iterable as Array [1,2,3]
participant Iterator as Iterator
Loop->>Iterable: Symbol.iterator
Iterable->>Iterator: Return iterator
Loop->>Iterator: next()
Iterator->>Loop: { value: 1, done: false }
Loop->>Iterator: next()
Iterator->>Loop: { value: 2, done: false }
Loop->>Iterator: next()
Iterator->>Loop: { value: 3, done: false }
Loop->>Iterator: next()
Iterator->>Loop: { value: undefined, done: true }
TopicDescriptionEst. Time
Iteration ProtocolIterable, iterator, next()15 min
Custom IterablesImplementing Symbol.iterator15 min
  • Symbols (Symbol.iterator)
  • Loops and iteration
  • Understanding of objects
Iteration Protocol → Custom Iterables