The Iterator Protocol is a standardized way to produce a sequence of values, one at a time, on demand. It allows objects to define their iteration behavior, such as what values are looped over in a for...of loop.

💡 Core Concept
An object is an iterator if it implements a next() method that returns an object with two properties: value and done.
Iterator Interface
next(): Returns an object{ value, done }.value: The next value in the sequence.done: Boolean,trueif iteration is complete, otherwisefalse.
📌 Deep Dive: Basic Iterator Object
const iterator = {
current: 1,
last: 3,
next() {
if (this.current <= this.last) {
return { value: this.current++, done: false };
} else {
return { done: true };
}
}
};
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { done: true }
{ value: 2, done: false }
{ value: 3, done: false }
{ done: true }
Iterable vs Iterator
An iterable is an object that implements the @@iterator method, accessible via Symbol.iterator, which returns an iterator.
The iterator is the object that actually produces the sequence via next().
| Property | Iterable | Iterator |
|---|---|---|
Has Symbol.iterator | Yes | Usually no |
Has next() | No | Yes |
| Returns | Iterator | Sequence values |
| Used in | for...of, spread operator | Manual iteration |
Making an Object Iterable
To make a custom object iterable (usable in for...of), implement the Symbol.iterator method that returns an iterator.
📌 Deep Dive: Custom Iterable Object
const iterable = {
start: 1,
end: 3,
[Symbol.iterator]() {
let current = this.start;
let last = this.end;
return {
next() {
if (current <= last) {
return { value: current++, done: false };
} else {
return { done: true };
}
}
};
}
};
for (const num of iterable) {
console.log(num);
}
// Output: 1 2 3
2
3
💡 Built-in Iterables
Arrays, Strings, Maps, Sets, and many other built-in objects implement the iterator protocol internally.
Why Use the Iterator Protocol?
- Enables
for...ofloops over custom data structures. - Allows lazy evaluation of values one at a time.
- Supports interoperability between different data types.
⚠️ Important
Do not confuse the iterator protocol with the iterable protocol. The iterable protocol requires Symbol.iterator returning an iterator; the iterator protocol requires a next() method.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
According to the Iterator protocol, which method is required to be implemented on an object for it to be considered an iterator?
Question 2 of 2
What does the done property indicate in the iterator's next() return value?
Loading results...