Making Objects Iterable with Symbol.iterator
You'll learn how to make any plain object work seamlessly with for...of loops by adding a [Symbol.iterator] method.
The Core Idea
By default, plain objects aren't iterable—you can't loop over them with for...of. But you can make them iterable by adding a special method using the well-known symbol Symbol.iterator. This method should return an iterator object (with a next() method that produces { value, done } results).
Think of it like installing a "tour guide" in your object that knows how to walk visitors through its contents step by step.
How It Works
When you add [Symbol.iterator] as a method on your object, JavaScript will automatically call it whenever something tries to iterate over your object (like for...of, spread operator, or destructuring).
const team = {
members: ['Alice', 'Bob', 'Charlie'],
[Symbol.iterator]() {
let index = 0;
const members = this.members;
return {
next() {
if (index < members.length) {
return { value: members[index++], done: false };
}
return { done: true };
}
};
}
};
// Now your object works with for...of!
for (const member of team) {
console.log(member); // Alice, Bob, Charlie
}
// And with spread operator
const allMembers = [...team]; // ['Alice', 'Bob', 'Charlie']
The [Symbol.iterator] method returns an iterator that tracks its own state (index) and produces values one at a time until exhausted.
Key Takeaway: Adding a [Symbol.iterator] method to any object makes it iterable, allowing it to work with for...of, spread syntax, and destructuring—transforming a plain object into something that can be elegantly traversed like arrays or strings.