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 theSymbol.iterator method that returns an iterator.
1. Custom Iterator
JavaScript Editor

Iterator Protocol:

  • next() method returns { value, done }
  • done: true signals iteration completion
  • Symbol.iterator makes 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
FeatureIteratorsGenerators
DefinitionObject with next() methodFunction with function*
SyntaxManual implementationyield keyword
State ManagementManualAutomatic (paused/resumed)
Two-way CommNoYes (via next(value))
Use CasesCustom data structuresLazy eval, async, state machines