Generators and Iterators are features in JavaScript that allow you to control the flow of iteration — they let you pause and resume function execution, producing values one at a time instead of all at once.
1️⃣ Iterators
An iterator is an object that defines a sequence and returns one value at a time when its next() method is called.
Iterator Protocol
An object is an iterator if it has a next() method that returns:
{ value: <any>, done: <boolean> }
Example:
function createIterator(arr) {
let index = 0;
return {
next: function () {
return index < arr.length
? { value: arr[index++], done: false }
: { done: true };
},
};
}
const iterator = createIterator(["a", "b", "c"]);
console.log(iterator.next()); // { value: "a", done: false }
console.log(iterator.next()); // { value: "b", done: false }
console.log(iterator.next()); // { value: "c", done: false }
console.log(iterator.next()); // { done: true }
✅ Iterators are the foundation for for...of loops and iterable objects like arrays, maps, and sets.
2️⃣ Generators
A generator is a special function that automatically creates an iterator.
Defined using function*, it can pause execution (yield) and resume later (next()).
Example:
function* generatorExample() {
yield 1;
yield 2;
yield 3;
}
const gen = generatorExample();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
✅ The generator function yields one value at a time — it pauses between yields until next() is called again.
3️⃣ Passing Values into Generators
You can also send values back into a generator:
function* greet() {
const name = yield "What's your name?";
yield `Hello, ${name}!`;
}
const gen = greet();
console.log(gen.next().value); // "What's your name?"
console.log(gen.next("Teekam").value); // "Hello, Teekam!"
4️⃣ Real Use Cases
- Lazy data generation
- Asynchronous control flow (before async/await)
- Managing complex iterations (e.g., custom sequence generators)
💡 In Short:
- Iterator: An object that returns values using
.next().- Generator: A function (
function*) that automatically creates an iterator usingyield.
Together, they provide a powerful way to manage sequential data and asynchronous operations in JavaScript.