What You'll Learn
You'll learn how the Symbol.iterator method enables any object to define its own custom iteration behavior, making it compatible with for...of loops and other iteration-consuming constructs.
The Symbol.iterator Method Explained
When you use a for...of loop on an array or string, JavaScript looks for a special method on that object—a method identified by the Symbol.iterator key. This method must return an iterator object (an object with a next() method that follows the iterator protocol).
Think of Symbol.iterator as a "how to loop over me" instruction manual that you attach to an object. When JavaScript needs to iterate, it calls this method to get the iterator, then repeatedly calls next() until iteration is complete.
Why This Matters
By defining a Symbol.iterator method on your custom objects, you make them iterable just like built-in types:
const countToThree = {
[Symbol.iterator]() {
let count = 1;
return {
next() {
if (count <= 3) {
return { value: count++, done: false };
}
return { done: true };
}
};
}
};
for (const num of countToThree) {
console.log(num); // 1, 2, 3
}
Without Symbol.iterator, attempting for...of on an object throws an error. With it, you control exactly what values get produced and in what order.
The Method's Job
The Symbol.iterator method itself doesn't do the iterating—it's a factory that returns an iterator. Each time JavaScript starts a new iteration (like a new for...of loop), it calls Symbol.iterator to get a fresh iterator object.
Key Takeaway: The Symbol.iterator method is how you teach JavaScript how to iterate over your custom objects—it returns an iterator that controls what values are yielded and when iteration stops.