What are Iterators?
An iterator is an object that knows how to access items from a collection one at a time, while keeping track of its current position. This is the mechanism that powers
for...of loops and the spread operator.javascript
Creating Custom Iterators
You can make any object "iterable" by implementing the
Symbol.iterator method. This method must return an object with a .next() method.javascript
Generators: A Cleaner Approach (function*)
Wait! Writing custom iterators is complex. Generators provide a much simpler way to define iteration logic using the
function* syntax and the yield keyword.- Starts running only when you call
.next(). - Returns the value and pauses execution at each
yield. - Remembers its state!
javascript
Why Use Generators?
- Infinite Sequences: You can represent data that never ends (like a sequence of IDs) without crashing your computer.
- Lazy Evaluation: Only calculates what you need, right when you need it.
- Memory Efficient: You don't need to store a million-item list in your RAM.
Async Generators (ES2018+)
You can even combine generators with asynchronous logic to iterate through a data stream (like an API that returns results page-by-page).
javascript
Summary
| Feature | Method / Syntax | Purpose |
|---|---|---|
| Iterator | [Symbol.iterator] | The protocol for loops |
| Generator | function* | Easy way to create iterators |
| Yield | yield x | Pause and return a value |
| Async Gen | async function* | Iterate over async streams |
| Next | .next() | Move to the next step |
| Best For | Streams, infinite data, custom collection types | |
| Memory | O(1) space (High performance!) | |
| Lazy | Only computes what's needed | |
| Return | return v | Stop the generator and return v |
| Throw | g.throw(err) | Trigger an error INSIDE the generator |
| Send | g.next(val) | Send data BACK into the generator |
| Delegate | yield* another() | Yield items from another generator |
| Native | Arrays, Maps, Sets are all Iterables! | |
| Comprehension | Generators are the building blocks for modern async code |