Understanding Iterators
Understanding Iterators in Modern JavaScript
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.
1. The Two Iteration Protocols
1. The Iterable Protocol
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.
2. 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 (falsewhile iteration continues,truewhen exhausted).
2. Built-in Iterables
JavaScript includes many built-in iterables:
- Arrays:
[1, 2, 3] - Strings:
'hello'(iterates over Unicode code points) - Maps:
new Map([['a', 1]])(iterates over[key, value]pairs) - Sets:
new Set([1, 2, 3]) - DOM NodeLists:
document.querySelectorAll('div') - Arguments object: function
arguments
3. How for...of Uses Iterators Internally
The for...of loop is syntactic sugar that manages iterators automatically:
4. Why Plain Objects are NOT Iterable by Default
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:
Practice Quiz
Creating Custom Iterators
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Practical Use Cases | Creating Custom Iterators |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.