What are generators and iterators in JavaScript?
Learn how iterators define custom iteration behavior and how generators make writing them easier.
Question
What are generators and iterators in JavaScript?
Answer
An iterator is an object that defines a sequence and returns a value on each call to next().
const iterator = [1, 2, 3][Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
A generator is a special function (declared with function*) that makes writing iterators easier.
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
const gen = idGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
Generators:
- Pause and resume execution
- Are great for producing sequences
- Power async flows (with older libraries)
Real-World Example
You can use generators to lazily load data or paginate large lists without loading everything at once.
Quick Practice
Create a generator that yields Fibonacci numbers one by one.
Summary
Iterators define “how to loop”. Generators make building iterators simple and readable.
Do I always need generators for iteration?
No. They’re just a convenient way to create iterables. Arrays, strings, Maps, and Sets are already iterable.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.