Generators and iterators are two powerful features in JavaScript that allow you to work with sequences of data and control execution in more flexible, memory-efficient ways. With their introduction in ES6, developers gained the ability to pause and resume functions, or to define custom iteration logic for their own data structures.
What Are Iterators?
An iterator is an object with a next() method that returns the next value in a sequence. This method always returns an object with two properties:
- value: The next value in the sequence.
-
done: A
booleanindicating if all values have been iterated.
Example: Creating a manual iterator for a range of numbers:
js
function makeRangeIterator(start = 0, end = 3, step = 1) {
let nextIndex = start;
return {
next: function() {
if (nextIndex < end) {
return { value: nextIndex++, done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
const iterator = makeRangeIterator(1, 5, 1);
let result = iterator.next();
while (!result.done) {
console.log(result.value); // 1 2 3 4
result = iterator.next();
}
Iterators are the foundation of the for...of loop and can be implemented on any custom object by defining the [Symbol.iterator]() method.
What Are Generators?
Generators are special functions that can pause and resume their execution. A generator is defined with function* syntax and uses the yield keyword to output values one at a time.
Example: A simple generator yields three numbers:
js
function* generateNumbers() {
yield 10;
yield 20;
yield 30;
}
const gen = generateNumbers();
console.log(gen.next().value); // 10
console.log(gen.next().value); // 20
console.log(gen.next().value); // 30
- Each call to
next()resumes execution until the next yield. - Generators return an iterator object automatically and can be used in
for...ofloops. Generators make it much easier to write complex iteration logic, as they encapsulate their own state and enable clean, readable code for workflows that require pausing between steps.
Comparing Iterators and Generators
| Feature | Iterator | Generator |
|---|---|---|
| Creation | Manual implementation of next()
|
function* and yield automates iteration |
| State management | Explicit (handled by the developer) | Handled internally by function's closure |
| Ease of use | Can be verbose for complex sequences | Simple and concise for even complex patterns |
| Used in for...of loop | Yes, if [Symbol.iterator] is defined |
Yes (generators are iterable) |
Why Use Them?
Use iterators when you need explicit control over sequential retrieval from a custom data structure or want to control iteration protocol manually.
Use generators to easily define sequences, pause and resume execution, and simplify complex iterative processes, such as infinite streams, asynchronous flows, or tree traversal.
Stay tuned for more insights as you continue your journey into the world of web development!
Check out theYouTubePlaylist for great JavaScript content for basic to advanced topics.
Please Do Subscribe Our YouTube Channel for clearing programming concept and much more ...CodenCloud
Top comments (0)