Hello! Welcome back to our second module on iteration.
In our previous lesson, we established the crucial distinction between the iterable protocol and the iterator protocol. You learned that an iterable is a data source that acts as a factory for iterators, and an iterator is the worker that produces a sequence of values. This separation of concerns is the foundation of JavaScript's powerful and consistent iteration model.
Today, we move from theory to practice. Your learning outcome is to: Implement the iterator protocol manually on a custom object using Symbol.iterator.
We will take the abstract rules we've learned and use them to make our own objects and classes compatible with standard JavaScript iteration mechanisms like the for...of loop and the spread syntax (...). By the end of this lesson, you will be able to:
- Define the
[Symbol.iterator]()method on a custom object. - Implement the iterator object, including the stateful
next()method. - Structure this implementation within an ES6 class, a common and robust pattern.
- Understand the importance of creating fresh, independent iterators for each iteration.
Building iterators manually will give you a deep appreciation for the mechanics of iteration and will perfectly set the stage for our next lesson, where we'll discover a much simpler syntax for achieving the same result.
1. The Core Implementation Pattern
Let's quickly recap the contract from our last lesson. To make any object iterable, it must have a method whose key is the well-known symbol Symbol.iterator.
- The Iterable: Your custom object needs a
[Symbol.iterator]()method. - The Iterator Factory: This method's job is to return a new iterator object.
- The Iterator: The returned iterator object must have a
next()method. - The Result: The
next()method returns a result object of the form{ value: ..., done: ... }.
This relationship is the blueprint for everything we will build in this lesson.

This diagram shows the fundamental pattern: An Iterable contains a [Symbol.iterator]() method that, when called, produces an Iterator. The Iterator is the object that actually has the next() method used for traversal.
2. Manually Creating an Iterable Object
Let's start by making a simple custom object iterable. The following video provides a clear, step-by-step demonstration of this process. It starts by manually getting an iterator from a built-in array (a good refresher) and then applies the same logic to a custom object.
How To Use Iterators in JavaScript - Iterate Over Arrays and Collections
This video from dcode, titled 'How To Use Iterators in JavaScript', is a great practical starting point. It will walk you through the process of accessing an iterator and then building your own.
Please watch the two segments from 01:39 to 07:06 and from 11:03 to 15:28. The first part recaps how to get an iterator from an array. The second part shows how to implement Symbol.iterator on a custom object to make it work with for...of loops.
As you saw in the video, the key is this nested structure:
- The
[Symbol.iterator]function is defined on the main object. - It uses a closure to hold the state of a single iteration (e.g.,
currentIndex). - It returns a new object—the iterator—which contains the
next()method that advances this state.
3. A More Structured Approach: The Iterable Class
While the previous example works, a more common and robust pattern, especially for complex objects, is to use an ES6 class. This allows you to neatly encapsulate the data and the iteration logic together. Your CS background makes you familiar with classes as blueprints for objects, and in JavaScript, they can also serve as blueprints for iterable objects.
The following article provides an excellent example of a MyRange class that generates a sequence of numbers.
Mastering JavaScript Iteration: A Deep Dive into Symbol.iterator
The article 'Mastering JavaScript Iteration' from Kitemetric demonstrates a clean, class-based implementation of an iterable. We'll focus on the MyRange example.
Read the code example under the 'Basic Custom Iterable' section, which defines the MyRange class. Pay close attention to where the iteration state (current) is defined and how this is used to access the range's start and end.
Let's analyze the structure of the MyRange class:
class MyRange {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
// 1. State for this specific iteration is created here.
let current = this.start;
const end = this.end; // Accessing instance properties.
// 2. Return the iterator object.
return {
next() {
if (current <= end) {
// 3. Produce the next value and advance state.
return { value: current++, done: false };
} else {
// 4. Signal that the iteration is complete.
return { done: true };
}
}
};
}
}
const range = new MyRange(1, 3);
// The for...of loop works automatically!
for (const number of range) {
console.log(number); // Outputs: 1, 2, 3
}
// So does the spread operator.
console.log([...range]); // Outputs: [1, 2, 3]
The Importance of Fresh Iterators
A critical detail in the MyRange implementation is that the state variable let current = this.start; is declared inside the [Symbol.iterator]() method. This ensures that every time the for...of loop (or any other iteration mechanism) asks for an iterator, it gets a new one with its own independent state, starting from the beginning.
This prevents different iterations over the same object from interfering with each other. For example:
const range = new MyRange(1, 3);
// The first for...of loop gets its own iterator.
for (const num of range) {
console.log(`First loop: ${num}`);
}
// Outputs: First loop: 1, First loop: 2, First loop: 3
// The second loop gets a new, fresh iterator.
for (const num of range) {
console.log(`Second loop: ${num}`);
}
// Outputs: Second loop: 1, Second loop: 2, Second loop: 3
If [Symbol.iterator]() returned a shared iterator (e.g., by returning this and having the current state as a property of the MyRange instance), the second loop would find the iterator already exhausted and would produce nothing.
Test your understanding!
Your task is to create an iterable Matrix class. The constructor will accept a 2D array. When iterated over, the matrix should yield its elements one by one, in row-major order (i.e., traverse the first row, then the second, and so on).
class Matrix {
constructor(matrix) {
this.data = matrix;
this.height = matrix.length;
this.width = matrix[0].length;
}
// Your implementation of [Symbol.iterator]() goes here.
}
const myMatrix = new Matrix([
[1, 2],
[3, 4],
]);
// This should output: 1, 2, 3, 4
for (const element of myMatrix) {
console.log(element);
}
Hint: The iterator will need to keep track of two pieces of state: the current row and the current column.
Show answer
Here is a possible implementation:
class Matrix {
constructor(matrix) {
this.data = matrix;
this.height = matrix.length;
this.width = matrix.length > 0 ? matrix[0].length : 0;
}
[Symbol.iterator]() {
let y = 0; // row index
let x = 0; // column index
const data = this.data; // Capture `this.data` for use in the closure
const height = this.height;
const width = this.width;
return {
next: () => {
if (y >= height) {
// We've gone past the last row
return { done: true };
}
const value = data[y][x];
// Advance to the next position
x++;
if (x >= width) {
// End of a row, move to the start of the next row
x = 0;
y++;
}
return { value: value, done: false };
}
};
}
}
const myMatrix = new Matrix([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]);
console.log([...myMatrix]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
This solution correctly encapsulates the x and y state variables within the closure created by the [Symbol.iterator] method, ensuring a fresh iterator for each loop.
Conclusion
In this lesson, you've bridged the gap between theory and practice by manually implementing the iterator protocol. This is a significant step in mastering JavaScript's advanced features.
Key Takeaways:
- An object becomes iterable by implementing a method keyed by
Symbol.iterator. - This method is a factory that must return a fresh iterator object.
- The iterator object contains the core logic in its
next()method, which manages state and returns{ value, done }pairs. - Using an ES6 class provides a structured and reusable way to create custom iterable types.
- Proper state management is key: iteration state should be local to each iterator to allow for multiple, non-interfering traversals of the same iterable object.
As you might have noticed, writing the next method, managing state, and handling the done condition involves a fair amount of boilerplate code. What if there was a way to just "pause" a function and "yield" a value, and have JavaScript manage the state machine for us?
Next Up
That is precisely what we'll explore in our next lesson. We will introduce generator functions (function*), a powerful ES6 feature that provides a vastly simplified and more elegant syntax for creating iterators. You will learn how to use the yield keyword to create the exact same iterable objects we built today, but with much less code.