Custom iteration
Implement a custom object whose values can be consumed with for...of.
JS Puzzles · Const
The iterator protocol standardizes objects that produce sequence values through next(). Each call returns an IteratorResult with value and done, while the iterable protocol lets language constructs obtain the iterator.
An iterator is an object whose next() method produces a sequence one result at a time. Each result uses value for the current item and done to indicate completion; an iterable exposes [Symbol.iterator]() so iteration constructs can obtain that iterator.
iterator.next(value?)| Name | Type | Description |
|---|---|---|
value | any | An optional value passed to next(); the protocol permits zero or one argument. |
next() returns an IteratorResult object containing value and done.
const counter = {
current: 1,
next() {
return this.current <= 3
? { value: this.current++, done: false }
: { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
}
};
for (const value of counter) console.log(value);The object is both an iterator and an iterable: next() supplies IteratorResult objects, while [Symbol.iterator]() returns the iterator used by for...of.
Implement a custom object whose values can be consumed with for...of.
Read a sequence manually when explicit control over advancement is needed.
Represent lazy or potentially infinite data without creating all values up front.
Iterable protocolIteratorResultSymbol.iteratorfor...ofGenerators