Lesson 79 – JavaScript Iterators vs Generators
In the previous lesson, you learned about generators. In this lesson, we’ll compare iterators and generators in JavaScript. Understanding their differences helps you decide which one to use depending on the situation.
What You Will Learn
- What iterators are
- How to create custom iterators manually
- How generators simplify iterator creation
- Practical comparison of iterators and generators
Recap: What is an Iterator?
An iterator is an object that follows a specific protocol:
- It has a
next()
method. next()
returns an object with:- a
value
property (the current value) - a
done
property (boolean indicating if iteration is complete)
- a
Example of a Manual Iterator
function createIterator(array) {
let index = 0;
return {
next: function () {
if (index < array.length) {
return { value: array[index++], done: false };
} else {
return { done: true };
}
}
};
}
const myIterator = createIterator(["a", "b", "c"]);
console.log(myIterator.next()); // { value: 'a', done: false }
console.log(myIterator.next()); // { value: 'b', done: false }
console.log(myIterator.next()); // { value: 'c', done: false }
console.log(myIterator.next()); // { done: true }
Generators Simplify Iterators
Generators do all this work for you with less code.
function* generatorFunction() {
yield "a";
yield "b";
yield "c";
}
const myGenerator = generatorFunction();
console.log(myGenerator.next()); // { value: 'a', done: false }
console.log(myGenerator.next()); // { value: 'b', done: false }
console.log(myGenerator.next()); // { value: 'c', done: false }
console.log(myGenerator.next()); // { value: undefined, done: true }
You don’t need to manually manage the state/index when using generators.
Comparing Iterators vs Generators
Feature | Iterator | Generator |
---|---|---|
Setup | Manual implementation | Uses function* syntax |
State Management | Done manually | Handled by generator engine |
Syntax | Verbose | Concise |
Use Cases | Full control, complex iteration | Easy iteration, lazy evaluation |
Use Cases
Use Case | Use This |
---|---|
Simple sequence generation | Generator |
Complex state-based iteration | Iterator |
Need lazy evaluation | Generator |
External state needed | Iterator |
Try Your Hand
Create a generator and an iterator that yield numbers from 1 to 3, then compare their output.
Summary
- Iterators follow a protocol (
next()
withvalue
anddone
). - Generators simplify iteration with
function*
andyield
. - Choose based on your need for simplicity or full control.