Iterators & Generators 🔁
Iterators are conveyor belts delivering items one by one; generators are factories that build those belts with minimal code.
Iterator Protocol 📜
- An object is iterable when it has a
[Symbol.iterator]method returning an iterator. - Iterator must implement
next()returning{ value, done }.
const countdown = {
from: 3,
[Symbol.iterator]() {
let current = this.from;
return {
next() {
if (current >= 0) {
return { value: current--, done: false };
}
return { value: undefined, done: true };
},
};
},
};
for (const num of countdown) {
console.log(num);
}Generators (function*) ⚙️
Generators automate iterator creation.
function* steps() {
yield "wake";
yield "stretch";
yield "code";
}
const routine = steps();
routine.next(); // { value: "wake", done: false }yieldpauses the function;next()resumes it.yield*delegates to another generator/iterable.
Passing Values In 🔄
function* conversation() {
const answer = yield "How are you?";
yield `You said ${answer}`;
}
const chat = conversation();
chat.next(); // prompt
chat.next("great"); // feed value backAsync Iteration 🕒
Pair with promises for streaming data (for await...of).
async function* stream() {
yield await fetchChunk();
}Use Cases 🎯
- Lazily generate sequences (ranges, Fibonacci, pagination).
- Implement custom data pipelines without building arrays.
- Power libraries like Redux-Saga, Immer, and data loaders.
Analogy: generators are choose-your-own-adventure books where each
yieldhands control back to the reader until they flip the next page.
Use them when you need fine-grained control over iteration or asynchronous flows. 📚
Last updated on