Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 4 · Lesson 40 · 5 min read

JavaScript Iterators and Generators Explained

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Paginated API and a Streaming Response
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Understand the iteration protocol behind for of, spread and destructuring, make objects iterable, write generator functions that produce values lazily, consume asynchronous streams with for await, and apply these tools to pagination, streaming responses and large data processing.

Concept Explanation

Many JavaScript features share one small contract, the iteration protocol. An object is iterable if it has a method under the key Symbol.iterator that returns an iterator. An iterator is an object with a next method that returns results shaped like { value, done }. for of loops, spread syntax, array destructuring, Array.from, Promise.all, and the Map and Set constructors all consume iterables through this protocol. Arrays, strings, maps, sets, NodeLists and the results of URLSearchParams and FormData are all iterable, which is why you can loop over all of them the same way.

Generator functions, written with function*, make iterators easy to write. Calling a generator does not run its body; it returns an iterator. Each call to next runs the body until the next yield, returns the yielded value and pauses with all local state intact. When the body returns, the iterator is done. Because values are produced only when asked for, generators are lazy: a generator can describe an infinite sequence, such as unique ids, or walk a huge tree, and a consumer that stops early with break never pays for the rest.

Laziness enables pipelines. Instead of building intermediate arrays with map and filter over a million items, generator functions can transform items one at a time. ECMAScript 2025 standardized iterator helpers such as map, filter, take, drop and toArray directly on iterators, so you can write numbers().filter(isPrime).take(10).toArray() without allocating large arrays, and support has reached all major browsers recently.

Asynchronous data has a parallel protocol. An async iterable has a Symbol.asyncIterator method, its iterator's next returns a promise, and for await of consumes it, waiting for each value. Async generators, written async function*, can await inside and yield values over time. This is a natural fit for paginated APIs, where each page requires a request, and for streams: a fetch response body is a ReadableStream, which is async iterable in current engines (older ones need a loop over body.getReader()), so you can process a large download or a streaming text response, such as tokens from an AI chat endpoint, as chunks arrive rather than waiting for the whole response.

Iteration can be stopped early. When a for of or for await loop exits through break, return or an exception, it calls the iterator's return method, which runs any finally block in the generator. That gives generators a reliable place for cleanup, such as cancelling the underlying request with an AbortController when the consumer stops reading.

ConceptSyntaxUse
Iterableobj[Symbol.iterator]()Works with for of, spread, destructuring
Iteratornext() returns { value, done }Step through values one at a time
Generatorfunction* with yieldLazy sequences with paused state
Iterator helpersiter.filter().map().take(n)Lazy pipelines without arrays
Async iterableobj[Symbol.asyncIterator]()Values that arrive over time
Async generatorasync function* with await and yieldPagination, polling, streams
for await offor await (const x of source)Consume async iterables
Early exitbreak calls return, runs finallyCleanup and cancellation

Worked Example: Paginated API and a Streaming Response

An async generator hides cursor pagination behind a simple loop and cancels the request if the consumer stops early. A second function reads a streaming text response chunk by chunk.

TypeScript
// Cursor pagination as one lazy async sequence
async function* fetchAllOrders({ pageSize = 50 } = {}) {
  const controller = new AbortController();
  let cursor = null;
  try {
    do {
      const url = `/api/orders?limit=${pageSize}${cursor ? `&cursor=${cursor}` : ''}`;
      const res = await fetch(url, { signal: controller.signal });
      if (!res.ok) throw new Error(`Orders failed with ${res.status}`);
      const page = await res.json();
      yield* page.items;                    // hand over items one at a time
      cursor = page.nextCursor;
    } while (cursor);
  } finally {
    controller.abort();                      // runs when the consumer breaks early
  }
}

// The consumer stops after finding what it needs; no further pages are requested
for await (const order of fetchAllOrders()) {
  if (order.status === 'failed') { showFailed(order); break; }
}

// Streaming text, for example an AI completion or a large log
async function streamInto(el, url) {
  const res = await fetch(url);
  const decoder = new TextDecoder();
  for await (const chunk of res.body) {     // ReadableStream is async iterable
    el.textContent += decoder.decode(chunk, { stream: true });
  }
  el.textContent += decoder.decode();       // flush the last partial character
}

// A lazy synchronous generator with iterator helpers
function* ids(prefix) { let n = 1; while (true) yield `${prefix}-${n++}`; }
const firstThree = ids('row').take(3).toArray();   // ['row-1', 'row-2', 'row-3']

The infinite ids generator is safe because take stops consumption after three values. The pagination generator reads like a single loop, yet it only fetches as many pages as the consumer actually uses.

The consumer loops with for await. The generator fetches a page only when items run out, yields items one at a time and follows the cursor. When the consumer breaks early, the generator's finally block runs and aborts any request in flight.
The consumer loops with for await. The generator fetches a page only when items run out, yields items one at a time and follows the cursor. When the consumer breaks early, the generator's finally block runs and aborts any request in flight.

Real-World Examples

  • Streaming chat interfaces such as those built on the OpenAI and Anthropic APIs read server-sent tokens incrementally from the response body stream so users see text appear immediately rather than after the whole completion, and their JavaScript SDKs expose these streams as async iterables consumed with for await.
  • The iterator helpers proposal reached stage 4 and was included in ECMAScript 2025, after shipping in Chrome 122 in 2024, bringing lazy map, filter, take and drop to every iterator without third-party libraries.
Key Takeawaysfor of, spread, destructuring and many APIs share the iteration protocol: an iterator with next returning value and done. Generators create lazy iterators that pause between yields, enabling infinite sequences and memory-efficient pipelines with iterator helpers. Async generators and for await turn pagination and streams into simple loops, and early exit runs finally so you can cancel underlying work.

Review Questions & Answers

It has a method under the Symbol.iterator key that returns an iterator, an object whose next method returns results of the form { value, done }. Any such object works with for of, spread, destructuring and Array.from.

Calling a generator only creates an iterator; the body runs up to each yield only when next is called. Values are computed on demand, so infinite sequences are possible and work stops as soon as the consumer stops asking.

It encapsulates the loop of requesting a page, yielding its items and following the next cursor. Consumers just write for await over the generator, and pages are fetched only as items are needed, stopping when the consumer breaks.

The loop calls the iterator's return method, which completes the generator as if a return statement ran at the paused yield, so any finally blocks execute. That is where cleanup such as aborting requests should go.