Sub topic 1
Refresher: How Iteration Works in JavaScript
Async iteration builds directly on the synchronous iteration protocol. for await...of, Symbol.asyncIterator, and async generators all reuse the same ideas, with promises added. This chapter reviews the sync protocol in detail so that the later chapters only have to explain what changes.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, objects, and arrays, including methods defined inside object literals.
- Basic
for...ofloops over arrays and strings. - Running scripts with Node.js (version 18 or later is fine) or pasting them into a browser console.
Promises and async/await are prerequisites for the tutorial as a whole. This chapter doesn't use them yet.
Two Roles: Iterable and Iterator
The iteration protocol defines two separate roles. Mixing them up is the most common source of confusion.
| Role | What it must have | Example |
|---|---|---|
| Iterable | A method under the key `Symbol.iterator` that returns an iterator | Arrays, strings, `Map`, `Set`, `arguments`, NodeLists |
| Iterator | A `next()` method that returns an object shaped like `{ value, done }` | The object returned by `[1, 2][Symbol.iterator]()` |
| Iterator result | A plain object with a `value` property and a boolean `done` property | `{ value: 1, done: false }` |
An iterable is something you can loop over. An iterator is the cursor that walks through it, one value at a time. Each call to [Symbol.iterator]() on an array gives you a fresh cursor that starts at the beginning, which is why you can loop over the same array many times.
Symbol.iterator is a well-known symbol: a built-in, unique key that the language itself looks up. Using a symbol rather than a string name like "iterator" means the protocol can't clash with ordinary property names on your objects.
Driving an iterator by hand
You rarely call next() yourself, but doing it once makes the protocol concrete:
const letters = ['a', 'b'];
const it = letters[Symbol.iterator]();
console.log(it.next()); // { value: 'a', done: false }
console.log(it.next()); // { value: 'b', done: false }
console.log(it.next()); // { value: undefined, done: true }
console.log(it.next()); // { value: undefined, done: true }Once an iterator reports done: true, it should keep reporting it. Nothing in the language enforces this, but every consumer assumes it.
What for...of Actually Does
A for...of loop is a fixed procedure built on the protocol:
- Evaluate the expression after
ofand call its[Symbol.iterator]()method. If the method doesn't exist, throw aTypeError. - Call
next()on the returned iterator. - If the result has
done: true, stop. Thevalueof that final result is ignored. - Otherwise, bind
valueto the loop variable, run the body, and go back to step 2.
The loop never asks how many items there are. It keeps calling next(), so an iterable can be lazy, computing each value only when asked, or even infinite.
Writing an Iterable by Hand
Here is a complete custom iterable. The range object is iterable because it has a [Symbol.iterator] method. That method returns a new iterator object each time it is called.
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
}
};
}
};
for (const n of range) {
console.log(n); // 1, 2, 3
}Several details here are deliberate:
[Symbol.iterator]()is a regular method, not an arrow function.for...ofcalls it asrange[Symbol.iterator](), sothisisrange. With an arrow function,thiswould come from the surrounding scope andthis.fromwould beundefined.fromandtoare copied into the local variablescurrentandlastwhen iteration starts. The iterator'snext()reads those through a closure, and each loop gets its own copy of the state.- Because each call returns a fresh iterator, two loops over
range, even nested ones, don't interfere with each other.
Other consumers of the protocol
for...of is only one consumer. Anything that accepts an iterable works with range:
console.log([...range]); // [1, 2, 3]
console.log(Array.from(range)); // [1, 2, 3]
const [first, second] = range;
console.log(first, second); // 1 2
console.log(Math.max(...range)); // 3
console.log(new Set(range).size); // 3Spread syntax, Array.from, array destructuring, new Map(), new Set(), Promise.all, and yield* all call [Symbol.iterator]() and then next(). If you implement the protocol once, all of them work.
Iterators That Are Also Iterable
Built-in iterators are themselves iterable. Their [Symbol.iterator]() method returns this. That lets you pass an iterator straight to for...of:
const it = ['x', 'y', 'z'][Symbol.iterator]();
it.next(); // consume 'x' manually
for (const v of it) {
console.log(v); // y, z
}
for (const v of it) {
console.log(v); // nothing: the iterator is exhausted
}This shows the difference between the two roles. An array can be iterated again and again because each loop gets a new iterator. An iterator is one-shot: once used up, it stays used up. Code that loops over the same iterator twice and expects data the second time is a common bug, and it shows up again with async sources such as streams.
Generators: The Shortcut
Writing next() by hand is verbose. A generator function, declared with function*, returns an object that is both an iterator and an iterable. Each yield produces one { value, done: false } result, and the function pauses until the next next() call.
function* rangeGen(from, to) {
for (let i = from; i <= to; i++) {
yield i;
}
}
for (const n of rangeGen(1, 3)) {
console.log(n); // 1, 2, 3
}
const gen = rangeGen(1, 2);
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: undefined, done: true }
console.log(gen[Symbol.iterator]() === gen); // trueYou can also make a reusable iterable with a generator method:
const range2 = {
from: 1,
to: 3,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) yield i;
}
};
console.log([...range2], [...range2]); // [1, 2, 3] [1, 2, 3]Async generators, covered later, use the same pausing model with await allowed inside.
Early Exit and return()
Iterators can define an optional return() method. for...of calls it when the loop ends before the iterator reports done: true, which happens through break, return, or an exception thrown in the loop body. It is not called when the iterator finishes normally.
function makeCounter(limit) {
let i = 0;
return {
[Symbol.iterator]() {
return this;
},
next() {
i++;
return i <= limit
? { value: i, done: false }
: { value: undefined, done: true };
},
return() {
console.log('return() called at', i);
return { value: undefined, done: true };
}
};
}
for (const n of makeCounter(5)) {
if (n === 2) break; // logs: return() called at 2
}
for (const n of makeCounter(2)) {
// runs to completion, return() is NOT called
}
const [a] = makeCounter(5); // destructuring stops early: return() called at 1
console.log(a); // 1For generators, return() comes for free and runs any finally blocks inside the generator. This is how iterators release resources such as file handles or network connections. The async version of this mechanism gets its own chapter, because cleanup matters most when the source is a real I/O resource.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: obj is not iterable` | Plain objects have no `[Symbol.iterator]` | Use `Object.entries(obj)`, `Object.keys(obj)`, or add the method |
| `TypeError: Result of the Symbol.iterator method is not an object` | The method returned nothing or a primitive | Return an object with a `next()` method |
| Loop runs forever | `next()` never returns `done: true`, or state isn't advanced | Update state on every call and check the end condition |
| Second loop produces nothing | Looping over the same iterator, or generator object, twice | Call the generator function again, or iterate the iterable instead |
| Values are `undefined` or `NaN` | Arrow function used for `[Symbol.iterator]`, so `this` is wrong | Use method syntax |
| `TypeError: Iterator result undefined is not an object` | `next()` returned nothing | Always return `{ value, done }` |
Where This Leads
The async protocol keeps the same structure with one change. Its next() returns a promise of { value, done } rather than the object itself, and the key is Symbol.asyncIterator. Keep the two roles, the one-shot nature of iterators, and the return() cleanup hook in mind. Each of them carries over directly into the next chapter.
Exercise
You write const iter = { [Symbol.iterator]: () => ({ next: () => ({ value: this.x, done: false }) }), x: 1 }; and spread it with [...iter]. Name the two problems with it.
Show answer
First, next() never returns done: true, so the spread never finishes and eventually runs out of memory. Second, the arrow functions take this from the surrounding scope rather than from iter, so this.x is not iter.x. At module or function scope it is undefined, or a lookup on undefined throws. Fix it with method syntax and an end condition.
Exercise
Given function* g() { yield 1; yield 2; } and const it = g();, what do [...it] and then [...it] again produce, and why does [...g()] twice behave differently?
Show answer
The first [...it] gives [1, 2] and the second gives [], because it is a one-shot iterator that is already exhausted. [...g()] calls the generator function each time and creates a fresh generator object, so it gives [1, 2] both times.
Exercise
Write a function take(iterable, n) that returns an array of at most the first n values, works with infinite iterables, and makes sure the source's return() runs when it stops early.
Show answer
function take(iterable, n) { const out = []; if (n <= 0) return out; for (const v of iterable) { out.push(v); if (out.length >= n) break; } return out; } The break makes for...of call the iterator's return(), so the source is closed. Checking n <= 0 first avoids pulling even one value when nothing is wanted.