Skip to content

Iterators and Generators

The iteration protocol, custom iterables, generator functions, and lazy data sequences.

What you'll learn

  • The iterable and iterator protocols (Symbol.iterator)
  • Creating custom iterable objects
  • Generator functions with function* and yield
  • Lazy evaluation and infinite sequences
  • Delegating with yield* and two-way communication via yield

Concept

The Iteration Protocol

An iterable is any object with a [Symbol.iterator] method that returns an iterator. An iterator is an object with a next() method that returns { value, done }. When you use for...of, the spread operator, or destructuring, JavaScript calls [Symbol.iterator] and repeatedly calls next() until done is true. Arrays, strings, Maps, and Sets are all built-in iterables.

Custom Iterables

You can make any object iterable by defining [Symbol.iterator] as a method that returns an iterator. This lets your custom objects work with for...of, spread, and Array.from() without inheriting from Array. The iterator's next() computes each value on demand, which means you can model sequences that are too large or infinite to store in an array.

Generator Functions

A generator is a function declared with function* that can pause and resume. The yield keyword produces a value and suspends execution; calling next() resumes from where it left off. Generators are a concise way to write iterators — the engine handles the { value, done } bookkeeping for you. Each yield becomes one step of the sequence.

Lazy and Infinite Sequences

Because generators compute values on demand, they can represent infinite sequences. A generator for natural numbers never finishes, but you can take the first N with a helper. This laziness avoids allocating a huge array up front and is the basis of efficient pipelines in libraries like RxJS. Values are produced only when consumed.

yield* Delegation

yield* delegates to another iterable or generator, flattening nested sequences. You can also send values back into a generator: const input = yield output receives whatever is passed to next(value). This two-way communication makes generators powerful enough to implement cooperative multitasking and coroutines, though async/await has largely replaced that use case.

Practical Relevance

You will most often encounter iterators through built-in iterables and the for...of loop. Writing custom generators is useful for paginated data, tree traversal, custom range objects, and any scenario where you want lazy, on-demand production of values. Understanding the protocol also demystifies how for...of and spread work under the hood.

Example

              // Custom iterable: a range of numbers
const range = {
  from: 1,
  to: 5,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        return current <= last
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};
console.log([...range]); // [1, 2, 3, 4, 5]
for (const n of range) console.log("range:", n);

// Generator: lazy infinite sequence of natural numbers
function* naturalNumbers() {
  let n = 1;
  while (true) yield n++;
}

// Take the first N from any iterable
function take(iterable, count) {
  const result = [];
  for (const value of iterable) {
    result.push(value);
    if (result.length >= count) break;
  }
  return result;
}
console.log("First 5 naturals:", take(naturalNumbers(), 5)); // [1, 2, 3, 4, 5]

// Generator with yield* delegation (flatten)
function* flatten(arr) {
  for (const item of arr) {
    if (Array.isArray(item)) yield* flatten(item);
    else yield item;
  }
}
const nested = [1, [2, [3, 4]], 5];
console.log("Flattened:", [...flatten(nested)]); // [1, 2, 3, 4, 5]

// Two-way communication: send values into a generator
function* accumulator() {
  let total = 0;
  while (true) {
    const input = yield total;
    total += input;
  }
}
const acc = accumulator();
acc.next(); // prime the generator
console.log(acc.next(10).value); // 10
console.log(acc.next(20).value); // 30
console.log(acc.next(5).value);  // 35
            

Shows a custom iterable range, a lazy infinite naturalNumbers generator, a take helper, yield* delegation to flatten nested arrays, and two-way communication sending values into a generator accumulator.

Try it

  • Text Counter

    Counting is a classic iteration task — generators can produce tokens lazily.

  • Line Deduplicator

    Iterating and deduplicating lines benefits from custom iterables.

Common mistakes

The mistake

Forgetting that a generator must be primed with next() before sending values

The fix

The first next() call runs the generator up to the first yield and cannot send a value. Call gen.next() once to prime it, then use gen.next(value) to send subsequent values into yield.

The mistake

Trying to spread an infinite generator into an array

The fix

Spreading [...gen] calls next() until done is true. An infinite generator never finishes, so this hangs. Use a take() helper or a for...of loop with a break to consume a finite number of values.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors