Iteration is the process of looping through elements of a collection one by one. In ES6, JavaScript formalized this process by introducing two core protocols: the Iterable Protocol and the Iterator Protocol. These protocols power fundamental language features such as for...of loops, the spread operator (...), and array destructuring.
An object is iterable if it defines an iteration behavior. It does this by implementing a method with the key Symbol.iterator:
[Symbol.iterator](): A zero-argument function that returns an object conforming to the Iterator Protocol.An object is an iterator if it implements a next() method:
next(): Must return an object with two properties:value: The current element value (any JS type).done: A boolean (false while iteration continues, true when exhausted).JavaScript includes many built-in iterables:
[1, 2, 3]'hello' (iterates over Unicode code points)new Map([['a', 1]]) (iterates over [key, value] pairs)new Set([1, 2, 3])document.querySelectorAll('div')argumentsThe for...of loop is syntactic sugar that manages iterators automatically:
Plain objects ({ a: 1, b: 2 }) do not have a [Symbol.iterator] method because the order of object keys was historically ambiguous, and it wasn't clear whether iteration should yield keys, values, or entries.
To iterate over objects with for...of, use helper methods:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Practical Use Cases | Creating Custom Iterators |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.