Reusable vs Single-Use Iterators
You'll learn: The crucial difference between iterators that can be used multiple times versus those that exhaust after one pass.
What's the Difference?
An iterable object can produce iterators. The key question is: does each call to [Symbol.iterator]() return a fresh, independent iterator, or does it return the same exhausted one?
- Reusable iterables: Every call to
[Symbol.iterator]()creates a new iterator, allowing you to iterate multiple times - Single-use iterables: The iterator exhausts after one pass, and subsequent iterations yield nothing
Think of it like a deck of cards. A reusable iterable is like having the full deck available—you can shuffle and deal as many times as you want. A single-use iterator is like dealing once and throwing the cards away.
Why It Matters
const reusable = {
data: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.data.length) {
return { value: this.data[index++], done: false };
}
return { done: true };
}
};
}
};
// Works every time!
for (let val of reusable) console.log(val); // 1, 2, 3
for (let val of reusable) console.log(val); // 1, 2, 3 again
Each for...of loop calls [Symbol.iterator]() and gets a new iterator with its own index, so both loops work independently.
If you return the same iterator or make the iterable return itself without resetting state, it becomes single-use and won't work on the second pass.
Key Takeaway: Always return a fresh iterator from [Symbol.iterator]() to make your iterables reusable across multiple iterations—never return this without resetting state.