Iterables and the Iterator Protocol
What you'll learn: You'll discover what makes an object iterable and why certain values work seamlessly with for...of loops.
The Core Idea
Not every JavaScript object can be used with for...of. The ones that can are called iterables—they follow a special contract called the Iterator Protocol. This protocol is like a set of rules that says, "If you implement these methods, JavaScript's looping mechanisms will know how to step through your values one at a time."
What Makes Something Iterable?
An object is iterable if it has a special method accessed via Symbol.iterator. When you use for...of on an object, JavaScript automatically calls this method to get an iterator—an object with a next() method that returns values sequentially.
Think of it like this: A book (iterable) has a bookmark system (iterator). Each time you say "next page," the bookmark moves forward and shows you the current page.
Built-In Iterables
Arrays, strings, Sets, and Maps are all iterables because they implement the Iterator Protocol behind the scenes. That's why for...of works naturally with them:
let arr = [10, 20, 30];
for (let value of arr) {
// Works because arrays are iterable
}
Plain objects {} are not iterable by default—that's why for...of throws an error with them. They don't have the Symbol.iterator method.
Why This Matters
Understanding iterables explains why for...of works with some values and not others. It's not magic—it's a protocol that JavaScript checks before allowing iteration.
Key Takeaway: An object is iterable if it implements the Iterator Protocol (has a Symbol.iterator method), which is why arrays, strings, Sets, and Maps work with for...of, but plain objects don't.