Building Your First Custom Iterator
You'll learn how to write a custom iterator from scratch for a simple data structure: a range of numbers.
Now that you understand the iterator protocol, it's time to put it into practice. A custom iterator lets you define how any object should be traversed step-by-step, making it work seamlessly with for...of, the spread operator, and other iteration tools.
The Core Idea
An iterator is just an object with a next() method that returns { value, done }. To make an object iterable, you give it a Symbol.iterator method that returns this iterator object.
Let's build a range iterator that produces numbers from start to end:
function createRange(start, end) {
let current = start;
return {
[Symbol.iterator]() {
return {
next() {
if (current <= end) {
return { value: current++, done: false };
}
return { value: undefined, done: true };
}
};
}
};
}
const range = createRange(1, 5);
for (const num of range) {
console.log(num); // 1, 2, 3, 4, 5
}
How It Works
The Symbol.iterator method returns an iterator object. That iterator's next() method tracks current and increments it each call. When current exceeds end, it returns done: true, signaling the iteration is complete.
Think of it like a ticket dispenser: each call to next() hands out the next ticket number until you run out.
You can now use your custom range with spread, destructuring, or any iterable-consuming operation:
const numbers = [...createRange(10, 12)]; // [10, 11, 12]
Key Takeaway: Building a custom iterator means implementing Symbol.iterator to return an object with a next() method that produces { value, done } objects—giving you full control over iteration behavior.