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:

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

See also