Lab 06: Iterators & Generators

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Master the iterator protocol, build custom iterables, use generator functions (function*), yield/yield*, infinite sequences, async generators, and for...of loops.


Step 1: Iterator Protocol

// An iterator is any object with a next() method
const manualIterator = {
  items: ['a', 'b', 'c'],
  index: 0,
  next() {
    if (this.index < this.items.length) {
      return { value: this.items[this.index++], done: false };
    }
    return { value: undefined, done: true };
  }
};

console.log(manualIterator.next()); // { value: 'a', done: false }
console.log(manualIterator.next()); // { value: 'b', done: false }
console.log(manualIterator.next()); // { value: 'c', done: false }
console.log(manualIterator.next()); // { value: undefined, done: true }

// Built-in iterables
const arr = [1, 2, 3];
const iter = arr[Symbol.iterator]();
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }

// String is iterable
for (const char of 'hello') {
  process.stdout.write(char + ' ');
}
console.log(); // h e l l o

💡 An iterable has [Symbol.iterator](). An iterator has next(). They can be the same object.


Step 2: Custom Iterable


Step 3: Generator Functions (function*)


Step 4: yield* and Delegation


Step 5: Infinite Sequences

💡 Generators are lazy — values are computed on demand. Perfect for infinite sequences and large datasets.


Step 6: Two-way Communication


Step 7: Async Generators


Step 8: Capstone — Lazy Pipeline

Run verification:

📸 Verified Output:


Summary

Concept
Syntax
Use Case

Iterator protocol

{ next() { return {value, done} } }

Custom iteration logic

Iterable

[Symbol.iterator]() { return iterator }

for...of, spread, destructure

Generator

function* gen() { yield v; }

Lazy sequences, coroutines

yield*

yield* iterable

Delegate to another iterable

Infinite sequence

while(true) { yield n++; }

Math sequences, IDs

Two-way

const v = yield expr

State machines, coroutines

Async generator

async function* gen()

Paginated APIs, streams

for await...of

for await (const x of asyncIter)

Consume async iterables

Last updated