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.
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.
next() returning
{ value, done }. Powers for...of, spread, and
destructuring.
function* creates a generator that pauses
at each yield and resumes on the next .next() call.
yield pauses and emits a value.
yield* delegates to another iterable, flattening it inline.
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.
// ── 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
[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.
* can go after
function or before the name — both are valid.
.next() call.return val inside a generator produces
{ value: val, done: true } — the terminal result.
// ── 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.
const g = gen() — creates the generator object.
The function body is not executed at all yet.yield expr, returns { value: expr, done: false }, and
freezes.
val becomes the result of the yield
expression that was paused. Execution continues until the next yield.return value produces
{ value: value, done: true }. for...of and spread skip
this value — only raw .next() calls see it.
.next() call returns
the same exhausted result. Generators are single-use — create a new one to
re-iterate.// ── 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.
// ── 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!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.
for await...of loops.
await sleep(ms) inside the
generator for rate-limited processing.
// ── 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.
Common Patterns & Recipes
These generator patterns appear repeatedly in real JavaScript codebases. Master them to write clean, memory-efficient, and highly composable code.
// ── 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"]
function* generator function return?yield and yield*?
- The iterator protocol defines two interfaces: an iterable exposes
[Symbol.iterator]()that returns an iterator; an iterator hasnext()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 eachyield. - A generator object is both an iterable and an iterator — its
[Symbol.iterator]()returnsthis, so it works directly infor...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 pausedyieldexpression — 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*) combineawaitandyield. Consume withfor await...offor streaming APIs, paginated fetches, and timed sequences.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.