Iterator
An Iterator
object is an object that conforms to the iterator protocol by providing a next()
method that returns an iterator result object. The Iterator.prototype
object is a hidden global object that all built-in iterators inherit from. It provides a @@iterator
method that returns the iterator object itself, making the iterator also iterable.
Note that Iterator
is not a global object, although it will be in the future with the iterator helpers proposal. The Iterator.prototype
object shared by all built-in iterators can be obtained with the following code:
js
const IteratorPrototype = Object.getPrototypeOf(
Object.getPrototypeOf([].values()),
);
Description
The following are all built-in JavaScript iterators:
- The Array Iterator returned by
Array.prototype.values()
,Array.prototype.keys()
,Array.prototype.entries()
,Array.prototype[@@iterator]()
,TypedArray.prototype.values()
,TypedArray.prototype.keys()
,TypedArray.prototype.entries()
,TypedArray.prototype[@@iterator]()
, andarguments[@@iterator]()
. - The String Iterator returned by
String.prototype[@@iterator]()
. - The Map Iterator returned by
Map.prototype.values()
,Map.prototype.keys()
,Map.prototype.entries()
, andMap.prototype[@@iterator]()
. - The Set Iterator returned by
Set.prototype.values()
,Set.prototype.keys()
,Set.prototype.entries()
, andSet.prototype[@@iterator]()
. - The RegExp String Iterator returned by
RegExp.prototype[@@matchAll]()
andString.prototype.matchAll()
. - The
Generator
object returned by generator functions. - The Segments Iterator returned by the
[@@iterator]()
method of theSegments
object returned byIntl.Segmenter.prototype.segment()
.
Each of these iterators have a distinct prototype object, which defines the next()
method used by the particular iterator. For example, all string iterator objects inherit from a hidden object StringIteratorPrototype
, which has a next()
method that iterates this string by code points. StringIteratorPrototype
also has a @@toStringTag
property whose initial value is the string "String Iterator"
. This property is used in Object.prototype.toString()
. Similarly, other iterator prototypes also have their own @@toStringTag
values, which are the same as the names given above.
All of these prototype objects inherit from Iterator.prototype
, which provides a @@iterator
method that returns the iterator object itself, making the iterator also iterable.
Instance methods
Iterator.prototype[@@iterator]()
-
Returns the iterator object itself. This allows iterator objects to also be iterable.
Examples
Using an iterator as an iterable
All built-in iterators are also iterable, so you can use them in a for...of
loop:
js
const arrIterator = [1, 2, 3].values();
for (const value of arrIterator) {
console.log(value);
}
// Logs: 1, 2, 3
Specifications
Specification |
---|
ECMAScript Language Specification # sec-%iteratorprototype%-object |
Browser compatibility
BCD tables only load in the browser