Iterables vs Iterators
You'll learn the crucial distinction between an iterable (the recipe book) and an iterator (the page-turner).
The Core Difference
An iterable is an object that has the ability to be iterated over—it contains a [Symbol.iterator] method that returns an iterator.
An iterator is the object doing the actual work—it has a next() method that returns {value, done} objects one at a time.
Think of it this way: an iterable is like a recipe book that can provide instructions, while an iterator is the bookmark that tracks your place as you read through it.
The Relationship
const myIterable = {
data: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
const data = this.data;
// This returned object is the ITERATOR
return {
next() {
if (index < data.length) {
return { value: data[index++], done: false };
}
return { done: true };
}
};
}
};
// myIterable is an ITERABLE (has Symbol.iterator)
const iterator = myIterable[Symbol.iterator]();
// iterator is an ITERATOR (has next())
console.log(iterator.next()); // { value: 1, done: false }
An Object Can Be Both
const iterableAndIterator = {
current: 0,
last: 3,
[Symbol.iterator]() {
return this; // Returns itself!
},
next() {
if (this.current <= this.last) {
return { value: this.current++, done: false };
}
return { done: true };
}
};
This object is both an iterable (has Symbol.iterator) and an iterator (has next()).
Key Takeaway: An iterable provides a [Symbol.iterator] method that produces iterators; an iterator provides a next() method that produces values. One object can fulfill both roles by returning itself from [Symbol.iterator].