Custom iterators
Create a custom sequence whose values are generated on demand.
JavaScript · Class
Iterator is the abstract base class for JavaScript iterator objects. Subclass it to implement next(), then use its iterable behavior and lazy helper methods to process sequences.
Iterator is an abstract base class for iterator objects. A subclass implements next() to produce iterator-result objects, while the class supplies iterable behavior and helper methods such as take(), map(), filter(), and toArray(); Iterator.from() can adapt an existing iterator or iterable.
class Subclass extends Iterator {
next() {
return { value, done };
}
}An Iterator subclass instance is an iterator object; the Iterator constructor page documents a new Iterator object as its return value, although Iterator itself is not intended to be instantiated directly.
class CountUp extends Iterator {
#current = 1;
next() {
return { value: this.#current++, done: false };
}
}
const numbers = new CountUp();
console.log(numbers.take(3).toArray()); // [1, 2, 3]A subclass supplies next(); iterator helpers can then lazily limit the sequence and materialize the requested values.
Create a custom sequence whose values are generated on demand.
Build memory-efficient transformation pipelines over potentially large or unbounded sequences.
Normalize iterator-like values supplied by libraries or application code.
Consume generated values with for...of, spread, or other iterable-based syntax.
Iterator is the base class for iterator objects. A subclass must implement next(), which returns an iterator result; Iterator also makes instances iterable by returning themselves from [Symbol.iterator]().
Follow-up: How would you adapt a library iterator? Use Iterator.from(), which returns an existing Iterator directly or wraps a non-Iterator iterator.
The constructor is intended as a superclass constructor rather than a directly usable class. Calling it without new throws, and constructing Iterator itself is not supported as a standalone operation.
Follow-up: What does Iterator.from() do for an iterable? It calls the iterable's [Symbol.iterator]() method and adapts the resulting iterator when necessary.
Iterator helpers are lazy iterator operations: they produce values only when the resulting helper's next() is requested. This allows transformations and limits to avoid eagerly creating an array.
Follow-up: What happens when a helper reaches the underlying iterator's end? The helper also completes and returns an iterator result with done set to true.
Iterator.from()Iterator.prototype[Symbol.iterator]()Iterator.prototype.map()Iterator.prototype.filter()Iterator.prototype.take()Iterator.prototype.toArray()Iteration protocols