Iterables and Generators
An iterable is an object you can walk with for...of, spread, and Array.from. A generator is a function that returns an iterator and can pause with yield.
Detailed Explanation
The iterable protocol is two methods. An object is iterable if it has [Symbol.iterator]() that returns an iterator. An iterator is an object with next() that returns { value, done }. done: true means the sequence is finished. That is the entire contract. Arrays, strings, Map, Set, typed arrays, arguments, and NodeList implement it.
for...of calls [Symbol.iterator](), then next() until done. Spread ([...iter]) and Array.from(iter) do the same and collect values. A plain object is not iterable. { a: 1 } thrown into for...of raises TypeError. Use Object.entries if you want its pairs.
You can implement the protocol yourself. A range object with [Symbol.iterator] that yields integers is a good example. The iterator can be the same object or a fresh one per call. If iterator === iterable, a second for...of continues where the first left off. Arrays return a new iterator each time, so they can be walked twice.
A generator function is declared with function* (or async function*). Calling it does not run the body. It returns a generator object that is both an iterator and an iterable. Each next() runs the body until the next yield or return. yield x produces x as the current value. return x produces x and sets done: true. yield* other delegates to another iterable.
Generators can also receive values: next(input) resumes, and the yield expression evaluates to input. gen.throw(err) injects an exception at the yield. These two features are how async libraries used to build control flow before async/await. You rarely need them for everyday iteration.
Async generators (async function* plus for await...of) yield promises. They are the right shape for paginated APIs and streams.
What it costs you: state. A custom iterator that mutates itself cannot be reused. A generator that closes over a large structure keeps it alive until the generator is exhausted or .return() is called. break from for...of calls the iterator's .return() if it exists, which is how generators clean up a try/finally.
Reach for for...of on any built-in collection. Reach for a generator when the sequence is large or infinite and you want to produce values lazily. Reach for a plain function that returns an array when the list is small and you want random access.
Code Examples
const letters = ["a", "b"];
for (const ch of letters) {
console.log(ch);
}
console.log([...letters]); // => [ 'a', 'b' ]
console.log(Array.from("hi")); // => [ 'h', 'i' ]function* range(start, end) {
for (let n = start; n < end; n += 1) {
yield n;
}
}
console.log([...range(2, 6)]); // => [ 2, 3, 4, 5 ]
const it = range(0, 2);
console.log(it.next()); // => { value: 0, done: false }
console.log(it.next()); // => { value: 1, done: false }
console.log(it.next()); // => { value: undefined, done: true }const countdown = {
from: 3,
[Symbol.iterator]() {
let n = this.from;
return {
next() {
if (n < 1) return { value: undefined, done: true };
const value = n;
n -= 1;
return { value, done: false };
},
};
},
};
console.log([...countdown]); // => [ 3, 2, 1 ]Common Gotchas
Plain objects are not iterable
`for (const x of { a: 1 })` throws. Use `Object.keys`, `Object.values`, or `Object.entries`.
A consumed generator is spent
calling `[...gen]` a second time yields `[]`. Produce a new generator (call `function*` again) for a second pass.
`break` and `return` close the iterator
a `try/finally` inside a generator still runs. That is good for cleanup; it is surprising if you thought the generator would stay paused.
`yield` is not `return`
the function pauses. After `return`, `done` is `true` and further `next()` calls stay done.