On this page
  1. Iterators, Generators & Iterator Helpers
  2. Contents
  3. The Iteration Protocol (Symbol.iterator)
  4. Generators (function*, yield, yield*)
  5. Lazy Iterator.prototype Helpers

Iterators, Generators & Iterator Helpers

Prev: ES Modules & Error Handling | Up: tutorials | Next: web
Rel: Proxy & Well-Known Symbols, Event Loop & Async Programming, Python Iterators and Generators
Ref: MDN Web Docs — Iterators and Generators
Tags: #public #web #javascript #tutorials #iterators #generators


Contents


The Iteration Protocol (Symbol.iterator)

An object is iterable if it defines [Symbol.iterator]() returning an iterator with a .next() method yielding { value, done }:

const range = (start, end) => ({
  [Symbol.iterator]() {
    let cur = start;
    return {
      next() {
        return cur < end ? { value: cur++, done: false } : { value: undefined, done: true };
      },
    };
  },
});

console.log([...range(1, 5)]); // [1, 2, 3, 4]

Generators (function*, yield, yield*)

Generator functions pause and resume lazily on yield, and delegate to nested iterables with yield*:

function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

function* flatten(items) {
  for (const item of items) {
    if (Array.isArray(item)) yield* flatten(item);
    else yield item;
  }
}

console.log([...flatten([1, [2, [3, 4]], 5])]); // [1, 2, 3, 4, 5]

Lazy Iterator.prototype Helpers

Modern JavaScript provides lazy pipeline methods directly on iterators (.map(), .filter(), .take(), .drop(), .toArray()), avoiding intermediate array allocations:

const firstSixEvens = fibonacci()
  .filter((n) => n % 2 === 0)
  .take(6)
  .toArray();

console.log(firstSixEvens); // [0, 2, 8, 34, 144, 610]

Linked from

Related notes