Generators as Iterators
You'll learn how generator objects automatically work as iterators, making them compatible with for...of loops and other iterator-consuming features.
The Built-In Connection
When you call a generator function, it returns a generator object. Here's the key insight: that generator object already implements the iterator protocol. You don't need to manually add a Symbol.iterator method or write your own next() logic—generators handle all of that automatically.
Since generator objects are iterators, they work seamlessly with anything that expects an iterable: for...of loops, the spread operator, destructuring, and Array.from().
Generators Meet for...of
function* countToThree() {
yield 1;
yield 2;
yield 3;
}
// Generator objects work directly with for...of
for (let num of countToThree()) {
console.log(num);
}
// Logs: 1, 2, 3
The for...of loop automatically calls next() on the generator object behind the scenes, extracts each yielded value, and stops when done becomes true.
Why This Matters
Before generators, creating custom iterators required writing several lines of boilerplate code. Generators give you the same power in a much simpler syntax. The yield keyword handles the iterator protocol for you, pausing and resuming execution automatically.
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Use with for...of (with a break to avoid infinite loop)
for (let num of fibonacci()) {
if (num > 50) break;
console.log(num);
}
Key Takeaway: Generator objects are iterators by design—they implement the iterator protocol automatically, making them work directly with for...of and other iterable-consuming features without any extra setup.