JavaScript Tutorial: Generators & Iterators
Iterators, generator functions with yield, lazy sequences, infinite generators, and custom iterables.
Pausable functions
Generators are functions that can pause and resume. Instead of computing all values upfront, they produce one value at a time — on demand.
This is called **lazy evaluation**: values are computed only when needed. It's how Python's `range(1000000)` doesn't use gigabytes of memory, and how JavaScript streams work.
What you'll learn in this JavaScript generators & iterators tutorial
This interactive JavaScript tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- The iterator protocol — Before generators, let's understand iterators. An **iterator** is any object with a `next()` method that returns `{ valu…
- Generator functions with yield — `function*` (note the asterisk) creates a generator. `yield` pauses it and emits a value.
- Generators work with for...of — Generators implement the iterable protocol automatically — they work directly in `for...of`, spread, and destructuring.
- Infinite generators — Generators can be infinite — they never run out of values. You take as many as you need.
- yield* — delegate to another generator — `yield*` delegates to another iterable — generator, array, string, anything iterable.
- Two-way communication with generators — Generators can receive values through `next(value)`. The `yield` expression evaluates to that value:
- Custom iterable class — Make any class iterable by implementing `[Symbol.iterator]()` — a method that returns an iterator.
- Lazy pipeline with generators — Final challenge — no starter code.
JavaScript Generators & Iterators concepts covered
- Pausable functions