Tutorials JavaScript Iterators & Generators
Ch 54 / 78
Chapter 54 Advanced 9 min read JavaScript

Iterators & Generators

Iterators are the engine behind every for...of loop, spread expression, and destructuring assignment in JavaScript — a standard protocol that any object can implement. Generators are special functions that pause and resume execution at each yield point, making it trivial to produce infinite sequences, lazy data pipelines, and complex async control flows — without blocking the thread.

What you'll learn
The iterator protocol — iterable & iterator interfaces
Building custom iterables with Symbol.iterator
Generator functions, function* syntax, and yield
Two-way communication — yield expressions and next(value)
Infinite sequences, lazy pipelines, and delegation via yield*
Async generators and for await...of for streaming data

Iterators & Generators — At a Glance

These two features share the same foundation — the iterator protocol — but solve different problems. An iterator is any object with a next() method that returns { value, done } objects. A generator is a factory that produces iterators automatically, with pause-and-resume superpower baked in.

Iterator Protocol
Any object with a next() returning { value, done }. Powers for...of, spread, and destructuring.
Generator Functions
function* creates a generator that pauses at each yield and resumes on the next .next() call.
yield & yield*
yield pauses and emits a value. yield* delegates to another iterable, flattening it inline.
Async Generators
async function* yields Promises. Consume with for await...of to process streamed or paginated data.
Concept Syntax Returns Use for...of?
Iterator obj.next() { value, done } yes
Iterable obj[Symbol.iterator]() iterator object yes
Generator function* gen() generator object (is both iterable & iterator) yes
Async Generator async function* gen() async generator object for await...of

The Iterator Protocol

The iterator protocol is a contract. An object is an iterator if it has a next() method that returns a result object with two properties: value (the yielded value) and done (true when the sequence is exhausted). An object is iterable if it exposes [Symbol.iterator]() that returns an iterator.

Iterable
Has [Symbol.iterator]() → returns iterator
Array ✓
String ✓
Map / Set ✓
NodeList ✓
Plain Object {} ✗ (add manually)
Generator object ✓ both
Iterator
Has next() → { value, done }
next().value current yielded value
next().done false until exhausted
done = true sequence finished
return(val) optional — early termination
throw(err) optional — inject error
JavaScript — Manual Iterator & Custom Iterable
// ── Manual iterator (bare-bones) ─────────────────────────────
function makeCounter(from, to) {
let current = from;
return { // this object IS an iterator
next() {
return current <= to
? { value: current++, done: false }
: { value: undefined, done: true };
}
};
}

const counter = makeCounter(1, 3);
counter.next(); // { value: 1, done: false }
counter.next(); // { value: 2, done: false }
counter.next(); // { value: 3, done: false }
counter.next(); // { value: undefined, done: true }

// ── Custom iterable object ────────────────────────────────────
const range = {
from: 1,
to: 5,
[Symbol.iterator]() { // makes the object iterable
let n = this.from;
const end = this.to;
return {
next() {
return n <= end
? { value: n++, done: false }
: { value: undefined, done: true };
}
};
}
};

for (const n of range) console.log(n); // 1 2 3 4 5
[...range]; // [1, 2, 3, 4, 5]
const [a, b, c] = range; // a=1, b=2, c=3
Iterator vs Iterable
An iterable has [Symbol.iterator]() (produces a fresh iterator on demand). An iterator has next() (stateful cursor). A generator object is both — its [Symbol.iterator]() returns this, so you can use it directly in for...of without an outer wrapper.

Generator Functions — function*

A generator function is declared with function*. Calling it does not execute the body — it returns a generator object (an iterator). The body runs only when you call .next(), and it runs until it hits a yield, at which point it pauses and hands the yielded value back to the caller.

function*
Generator Declaration
Declares a generator function. The * can go after function or before the name — both are valid.
function* gen() { yield 1; }
yield
Pause & Emit
Pauses execution and returns a value to the caller. Resumes from the same point on the next .next() call.
yield 42; // { value: 42, done: false }
yield*
Delegation
Delegates iteration to another iterable. Every value from the inner iterable is yielded out as if it came from the outer generator.
yield* [1, 2, 3];
return
Final Value
A return val inside a generator produces { value: val, done: true } — the terminal result.
return "done"; // { value: "done", done: true }
JavaScript — Generator Fundamentals
// ── Basic generator ───────────────────────────────────────────
function* colours() {
yield "red";
yield "green";
yield "blue";
return "done"; // final — done: true
}

const gen = colours(); // body NOT executed yet
gen.next(); // { value: "red", done: false }
gen.next(); // { value: "green", done: false }
gen.next(); // { value: "blue", done: false }
gen.next(); // { value: "done", done: true } ← return value
gen.next(); // { value: undefined, done: true }

// ── for...of ignores the return value (done: true) ───────────
for (const c of colours()) console.log(c); // red green blue

// ── Spread and destructuring work too ────────────────────────
[...colours()]; // ["red", "green", "blue"]
const [first, second] = colours(); // "red", "green"

// ── yield* — delegate to another iterable ────────────────────
function* combined() {
yield* ["a", "b"]; // flattens the array inline
yield* colours(); // delegates to another generator
yield "end";
}
[...combined()]; // ["a", "b", "red", "green", "blue", "end"]

How yield Pauses & Resumes

Understanding the execution model is crucial. Each .next() call resumes the generator from where it was frozen, runs until the next yield (or return), then freezes again. You can also pass a value back in via next(value) — the value becomes the result of the yield expression inside the generator.

1
Call the generator function
const g = gen() — creates the generator object. The function body is not executed at all yet.
2
First .next() — runs to first yield
Execution begins from the top, runs until the first yield expr, returns { value: expr, done: false }, and freezes.
3
Subsequent .next(val) — resumes & passes value
val becomes the result of the yield expression that was paused. Execution continues until the next yield.
4
return statement — terminal result
return value produces { value: value, done: true }. for...of and spread skip this value — only raw .next() calls see it.
5
After exhaustion — always { value: undefined, done: true }
Once done, every subsequent .next() call returns the same exhausted result. Generators are single-use — create a new one to re-iterate.
JavaScript — Two-Way Communication via next(value)
// ── Two-way data flow ─────────────────────────────────────────
function* calculator() {
const x = yield "Enter first number:";
const y = yield "Enter second number:";
return x + y;
}

const calc = calculator();

calc.next(); // { value: "Enter first number:", done: false }
// first .next() has no arg — starts the generator
calc.next(10); // x = 10 — { value: "Enter second number:", done: false }
calc.next(32); // y = 32 — { value: 42, done: true }

// ── throw() — inject an error into the generator ─────────────
function* safe() {
try {
yield "waiting...";
} catch (e) {
console.log("Caught:", e.message);
yield "recovered";
}
}

const s = safe();
s.next(); // { value: "waiting...", done: false }
s.throw(new Error("oops")); // logs "Caught: oops"
// { value: "recovered", done: false }

// ── return() — terminate generator early ─────────────────────
function* nums() { yield 1; yield 2; yield 3; }
const n = nums();
n.next(); // { value: 1, done: false }
n.return(99); // { value: 99, done: true } — generator terminated
n.next(); // { value: undefined, done: true }

Infinite Sequences & Lazy Pipelines

Because generators are lazy — they compute each value only when asked — they can safely represent infinite sequences. No array is built in memory; values are produced one at a time on demand. This makes generators the ideal tool for pagination, streaming, event sourcing, and any produce-on-demand data pattern.

JavaScript — Infinite Sequences & Pipelines
// ── Infinite natural numbers ─────────────────────────────────
function* naturals(start = 1) {
while (true) yield start++; // never returns — infinite!
}

function take(n, iterable) { // take first n items
const result = [];
for (const val of iterable) {
result.push(val);
if (result.length === n) break;
}
return result;
}

take(5, naturals()); // [1, 2, 3, 4, 5]
take(5, naturals(10)); // [10, 11, 12, 13, 14]

// ── Fibonacci generator ──────────────────────────────────────
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
take(8, fibonacci()); // [0, 1, 1, 2, 3, 5, 8, 13]

// ── Lazy pipeline: map → filter → take ───────────────────────
function* map(fn, iterable) {
for (const x of iterable) yield fn(x);
}
function* filter(pred, iterable) {
for (const x of iterable) if (pred(x)) yield x;
}

const evenSquares = filter(
n => n % 2 === 0,
map(n => n * n, naturals())
);
take(5, evenSquares); // [4, 16, 36, 64, 100]
// Only computes values as needed — zero wasted memory!
Memory Efficiency
A generator producing naturals() uses O(1) memory regardless of how many values are requested. An equivalent array like [...naturals()] would run forever and crash the tab. Always use break or helper functions like take(n, gen) to consume infinite generators safely.

Async Generators & for await...of

An async generator is declared with async function*. It can use both await (for Promises) and yield (to emit values). Each .next() call returns a Promise that resolves to { value, done }. Consume async generators with for await...of.

Paginated API Fetching
Yield each page of results as it arrives, letting the consumer process records without loading everything into memory first.
Server-Sent Events / WebSocket
Wrap incoming event streams as async generators to consume them with clean for await...of loops.
File / Stream Processing
Read large files line-by-line without buffering the whole file — yield one chunk at a time from the underlying stream.
Timed / Throttled Sequences
Yield values at controlled intervals using await sleep(ms) inside the generator for rate-limited processing.
JavaScript — Async Generators
// ── Async generator — paginated fetch ────────────────────────
async function* fetchPages(baseUrl) {
let page = 1;
while (true) {
const res = await fetch(`${baseUrl}?page=${page}`);
const data = await res.json();
if (!data.length) return; // no more pages → done
yield data; // emit current page array
page++;
}
}

// Consume with for await...of ────────────────────────────────
(async () => {
for await (const page of fetchPages("https://api.example.com/items")) {
page.forEach(item => console.log(item.name));
}
})();

// ── Timed async sequence ─────────────────────────────────────
const sleep = ms => new Promise(r => setTimeout(r, ms));

async function* countdown(from) {
for (let i = from; i > 0; i--) {
await sleep(1000); // wait 1 s
yield i;
}
}

for await (const n of countdown(5)) {
console.log(n); // 5 … 4 … 3 … 2 … 1 (one per second)
}

Try It — Live Editor

Explore iterators and generators interactively below. Modify the examples — try custom ranges, add extra yield points, or experiment with next(value) to see two-way communication in action.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These generator patterns appear repeatedly in real JavaScript codebases. Master them to write clean, memory-efficient, and highly composable code.

JavaScript — Generator Recipes
// ── 1. Unique ID generator ────────────────────────────────────
function* idGen(prefix = "id") {
let n = 1;
while (true) yield `${prefix}-${n++}`;
}
const nextId = idGen("user");
nextId.next().value; // "user-1"
nextId.next().value; // "user-2"

// ── 2. Flatten nested iterables ──────────────────────────────
function* flatten(iterable) {
for (const item of iterable) {
if (item != null && typeof item[Symbol.iterator] === "function"
&& typeof item !== "string") {
yield* flatten(item); // recurse
} else {
yield item;
}
}
}
[...flatten([1, [2, [3, [4]]]])]; // [1, 2, 3, 4]

// ── 3. Zip two iterables ─────────────────────────────────────
function* zip(...iterables) {
const iters = iterables.map(i => i[Symbol.iterator]());
while (true) {
const results = iters.map(i => i.next());
if (results.some(r => r.done)) return;
yield results.map(r => r.value);
}
}
[...zip([1, 2, 3], ["a", "b", "c"])]; // [[1,"a"],[2,"b"],[3,"c"]]

// ── 4. Chunk array into pages ─────────────────────────────────
function* chunk(arr, size) {
for (let i = 0; i < arr.length; i += size) {
yield arr.slice(i, i + size);
}
}
[...chunk([1,2,3,4,5], 2)]; // [[1,2],[3,4],[5]]

// ── 5. Round-robin scheduler ─────────────────────────────────
function* roundRobin(...iterables) {
const iters = iterables.map(i => i[Symbol.iterator]());
while (iters.length) {
for (let i = iters.length - 1; i >= 0; i--) {
const { value, done } = iters[i].next();
if (done) { iters.splice(i, 1); continue; }
yield value;
}
}
}
[...roundRobin([1,2], ["a","b","c"])]; // [1,"a",2,"b","c"]
Quick Check
What does calling a function* generator function return?
Quick Check
What is the difference between yield and yield*?
Quick Check
What syntax is used to consume an async generator?
Chapter Summary
  • The iterator protocol defines two interfaces: an iterable exposes [Symbol.iterator]() that returns an iterator; an iterator has next() that returns { value, done } objects.
  • Built-in iterables include Arrays, Strings, Maps, Sets, and NodeLists. Plain objects ({}) are not iterable by default — you must add [Symbol.iterator]() manually.
  • A generator function (function*) returns a generator object without executing the body. The body runs only on .next() calls and pauses at each yield.
  • A generator object is both an iterable and an iterator — its [Symbol.iterator]() returns this, so it works directly in for...of, spread, and destructuring.
  • yield* delegates to another iterable, flattening all its values inline — equivalent to iterating the inner iterable and yielding each value.
  • Passing a value to .next(val) after the first call makes that value the result of the paused yield expression — enabling two-way communication with the generator.
  • Generators are lazy and can represent infinite sequences safely. No value is computed until requested — making them ideal for pipelines and on-demand data.
  • Async generators (async function*) combine await and yield. Consume with for await...of for streaming APIs, paginated fetches, and timed sequences.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel