Iterators & Generators
Understanding Iterators
Iterators are objects that implement the Iterator protocol (a next() method that returns { value, done }). They enable custom iteration behavior for objects.
Iterable Protocol: An object is iterable if it implements the
Symbol.iterator method that returns an iterator.1. Custom Iterator
JavaScript Editor
Iterator Protocol:
next()method returns{ value, done }done: truesignals iteration completionSymbol.iteratormakes object iterable
3. Advanced Generator Patterns
JavaScript Editor
Generators support two-way communication and delegation.
5. Built-in Iterables
JavaScript Editor
Many JavaScript built-ins are iterable by default.
2. Generator Basics
JavaScript Editor
Generator Functions:
- Defined with
function* - Pause execution with
yield - Return iterator when called
4. Practical Use Cases
JavaScript Editor
Generators excel at lazy evaluation, async operations, and state machines.
6. Async Iterators & Generators
JavaScript Editor
Async iterators enable asynchronous iteration patterns.
Comparison Table
| Feature | Iterators | Generators |
|---|---|---|
| Definition | Object with next() method | Function with function* |
| Syntax | Manual implementation | yield keyword |
| State Management | Manual | Automatic (paused/resumed) |
| Two-way Comm | No | Yes (via next(value)) |
| Use Cases | Custom data structures | Lazy eval, async, state machines |