Iterator Reuse and the Iterable-Iterator Pattern
You'll learn why some iterables create fresh iterators every time, and when it makes sense to return the same iterator instance.
The Two Patterns
When you make an object iterable, you have two architectural choices:
1. Fresh Iterator Pattern (Most Common)
Your Symbol.iterator method returns a new iterator object each time it's called. This lets multiple consumers iterate independently without interfering with each other.
const team = {
members: ['Alice', 'Bob', 'Carol'],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.members.length) {
return { value: this.members[index++], done: false };
}
return { done: true };
}
};
}
};
// Two independent iterations work fine
for (const name of team) console.log(name); // Alice, Bob, Carol
for (const name of team) console.log(name); // Alice, Bob, Carol (starts fresh)
2. Iterable-Iterator Pattern (Reuse)
The object returns itself as the iterator. This is common when the iterable is the iterator (like manually calling .next() on an iterator).
const counter = {
current: 0,
max: 3,
[Symbol.iterator]() {
return this; // Return self
},
next() {
if (this.current < this.max) {
return { value: this.current++, done: false };
}
return { done: true };
}
};
for (const n of counter) console.log(n); // 0, 1, 2
for (const n of counter) console.log(n); // (nothing - already exhausted)
When to Choose Which
Use fresh iterators when the data source can be traversed multiple times. Use iterable-iterator for one-time-use sequences or when managing complex iteration state.
Key Takeaway: Most custom iterables should return a new iterator each time to allow independent, repeatable iteration—but returning this is valid for single-use or stateful iterators.