Iterators & Generators

In JavaScript, iterators are objects that provide a way to access elements sequentially without exposing the underlying structure. Generators are special functions that simplify iterator creation by yielding multiple values over time.

Illustration of Iterators & Generators
Illustration of Iterators & Generators

💡 What is an Iterator?

An iterator is an object with a next() method that returns an object with { value, done }. It allows controlled sequential access to data.

Iterator Example

📌 Deep Dive: Custom Iterator

JAVASCRIPT
const iterable = {
  data: ['a', 'b', 'c'],
  [Symbol.iterator]() {
    let index = 0;
    const data = this.data;
    return {
      next() {
        if (index < data.length) {
          return { value: data[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

for (const char of iterable) {
  console.log(char);
}
Output
a
b
c

💡 Symbol.iterator

The Symbol.iterator method defines the default iterator for an object, enabling it to be used with for...of loops and other iterable-consuming syntax.

Generators Simplify Iterators

Generators are functions declared with function* and use yield to produce values one at a time, pausing execution between each.

📌 Deep Dive: Generator Function

JAVASCRIPT
function* gen() {
  yield 1;
  yield 2;
  yield 3;
}

const generator = gen();

console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
Output
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }

Iterators vs Generators

Comparison
FeatureIteratorGenerator
ImplementationManually create next() methodUse function* and yield
State ManagementManual tracking of iteration stateAutomatic via generator's pause/resume
ReadabilityMore verbose and complexConcise and cleaner syntax
Use CaseCustom iteration logicEasy creation of iterables

⚠️ Important

Generators maintain their internal state between calls. Avoid calling next() after done: true, as it will not yield further values.

Practical Use: Infinite Sequence Generator

📌 Deep Dive: Infinite Number Generator

JAVASCRIPT
function* infiniteSequence() {
  let num = 0;
  while (true) {
    yield num++;
  }
}

const seq = infiniteSequence();

console.log(seq.next().value); // 0
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
Output
0
1
2

💡 Summary:

  • Iterators provide a standard protocol for sequential access.
  • Generators simplify creating iterators with less code.
  • Use Symbol.iterator to make objects iterable.
  • Generators can pause and resume execution, yielding multiple values.