What Symbol.iterator Provides
You'll learn how Symbol.iterator enables objects to work with JavaScript's iteration features like for...of loops and the spread operator.
The Core Idea
Symbol.iterator is a special well-known symbol that acts as a key on objects. When an object has a method at this key, that method returns an iterator object, which defines how to traverse through the object's values step-by-step. This is what makes arrays, strings, maps, and sets work with for...of loops and spread syntax (...).
Think of Symbol.iterator as a universal "how to loop through me" instruction manual that JavaScript knows to look for.
How It Connects Everything
When you write for (const item of myArray), JavaScript automatically:
- Looks for a method at
myArray[Symbol.iterator] - Calls that method to get an iterator object
- Uses the iterator to retrieve values one at a time
const arr = ['a', 'b', 'c'];
// Manually accessing what for...of does automatically
const iterator = arr[Symbol.iterator]();
console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: 'c', done: false }
console.log(iterator.next()); // { value: undefined, done: true }
The same mechanism powers the spread operator:
const letters = ['a', 'b', 'c'];
const copy = [...letters]; // Uses Symbol.iterator under the hood
Key Takeaway: Symbol.iterator is the protocol that allows objects to define their own iteration behavior, making them compatible with for...of, spread syntax, and other iteration-based features in JavaScript.