Iterators
Iterators
Section titled “Iterators”Introduction
Section titled “Introduction”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).
Learning Objectives
Section titled “Learning Objectives”- Understand the iteration protocol (iterable + iterator)
- Use
for...ofwith built-in iterables - Create custom iterables with
Symbol.iterator - Know which built-in types are iterable
Visual Summary
Section titled “Visual Summary”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 }Topics Covered
Section titled “Topics Covered”| Topic | Description | Est. Time |
|---|---|---|
| Iteration Protocol | Iterable, iterator, next() | 15 min |
| Custom Iterables | Implementing Symbol.iterator | 15 min |
Prerequisites
Section titled “Prerequisites”- Symbols (Symbol.iterator)
- Loops and iteration
- Understanding of objects
Learning Path
Section titled “Learning Path”Iteration Protocol → Custom Iterables