In JavaScript, iterators are objects that provide a way to access elements sequentially without exposing the underlying structure. Generators are special functions that simplify iterator creation by yielding multiple values over time.

💡 What is an Iterator?
An iterator is an object with a next() method that returns an object with { value, done }. It allows controlled sequential access to data.
Iterator Example
📌 Deep Dive: Custom Iterator
const iterable = {
data: ['a', 'b', 'c'],
[Symbol.iterator]() {
let index = 0;
const data = this.data;
return {
next() {
if (index < data.length) {
return { value: data[index++], done: false };
} else {
return { done: true };
}
}
};
}
};
for (const char of iterable) {
console.log(char);
}
b
c
💡 Symbol.iterator
The Symbol.iterator method defines the default iterator for an object, enabling it to be used with for...of loops and other iterable-consuming syntax.
Generators Simplify Iterators
Generators are functions declared with function* and use yield to produce values one at a time, pausing execution between each.
📌 Deep Dive: Generator Function
function* gen() {
yield 1;
yield 2;
yield 3;
}
const generator = gen();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }
Iterators vs Generators
| Feature | Iterator | Generator |
|---|---|---|
| Implementation | Manually create next() method | Use function* and yield |
| State Management | Manual tracking of iteration state | Automatic via generator's pause/resume |
| Readability | More verbose and complex | Concise and cleaner syntax |
| Use Case | Custom iteration logic | Easy creation of iterables |
⚠️ Important
Generators maintain their internal state between calls. Avoid calling next() after done: true, as it will not yield further values.
Practical Use: Infinite Sequence Generator
📌 Deep Dive: Infinite Number Generator
function* infiniteSequence() {
let num = 0;
while (true) {
yield num++;
}
}
const seq = infiniteSequence();
console.log(seq.next().value); // 0
console.log(seq.next().value); // 1
console.log(seq.next().value); // 2
1
2
💡 Summary:
- Iterators provide a standard protocol for sequential access.
- Generators simplify creating iterators with less code.
- Use
Symbol.iteratorto make objects iterable. - Generators can pause and resume execution, yielding multiple values.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What method must an iterator object implement?
Question 2 of 2
Which keyword is used inside a generator function to emit values?
Loading results...