Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Iterator

BaselineWidely available *

AnIterator object is an object that conforms to theiterator protocol by providing anext() method that returns an iterator result object. All built-in iterators inherit from theIterator class. TheIterator class provides a[Symbol.iterator]() method that returns the iterator object itself, making the iterator alsoiterable. It also provides some helper methods for working with iterators.

Description

The following are all built-in JavaScript iterators:

Web APIs may return iterators too. Some reuse core JavaScript iterators while others define their own iterators. For example:

  • Array-Like objects such asNodeList return anArray Iterator from their respective methodskeys(),values(),entries(), and[Symbol.iterator]().
  • Map-Like objects from Web APIs such asHeaders return their own iterator type likeHeaders Iterator from their respective methodskeys(),values(),entries(), and[Symbol.iterator]().
  • Set-Like objects from Web APIs such asFontFaceSet return their own iterator type likeFontFaceSet Iterator from their respective methodskeys(),values(),entries(), and[Symbol.iterator]().

Note:NodeIterator and other old interfaces are named as such but do not conform to theiterator protocol oriterable protocol.

Each of these iterators have a distinct prototype object, which defines thenext() method used by the particular iterator. For example, all string iterator objects inherit from a hidden objectStringIteratorPrototype, which has anext() method that iterates this string by code points.StringIteratorPrototype also has a[Symbol.toStringTag] property whose initial value is the string"String Iterator". This property is used inObject.prototype.toString(). Similarly, other iterator prototypes also have their own[Symbol.toStringTag] values, which are the same as the names given above.

All of these prototype objects inherit fromIterator.prototype, which provides a[Symbol.iterator]() method that returns the iterator object itself, making the iterator alsoiterable.

Iterator helper methods

Note:These methods areiterator helpers, notiterable helpers, because the only requirement for an object to be iterable is just the presence of a[Symbol.iterator]() method. There is no shared prototype to install these methods on.

TheIterator class itself provides some helper methods for working with iterators. For example, you may be tempted to do the following:

js
const nameToDeposit = new Map([  ["Anne", 1000],  ["Bert", 1500],  ["Carl", 2000],]);const totalDeposit = [...nameToDeposit.values()].reduce((a, b) => a + b);

This first converts the iterator returned byMap.prototype.values() to an array, then uses theArray.prototype.reduce() method to calculate the sum. However, this both creates an intermediate array and iterates the array twice. Instead, you can use thereduce() method of the iterator itself:

js
const totalDeposit = nameToDeposit.values().reduce((a, b) => a + b);

This method may be more efficient, especially memory-wise, because it only iterates the iterator once, without memorizing any intermediate values. Iterator helper methods are necessary to work with infinite iterators:

js
function* fibonacci() {  let current = 1;  let next = 1;  while (true) {    yield current;    [current, next] = [next, current + next];  }}const seq = fibonacci();const firstThreeDigitTerm = seq.find((n) => n >= 100);

You cannot convertseq to an array, because it is infinite. Instead, you can use thefind() method of the iterator itself, which only iteratesseq as far as necessary to find the first value that satisfies the condition.

You will find many iterator methods analogous to array methods, such as:

Iterator methodArray method
Iterator.prototype.every()Array.prototype.every()
Iterator.prototype.filter()Array.prototype.filter()
Iterator.prototype.find()Array.prototype.find()
Iterator.prototype.flatMap()Array.prototype.flatMap()
Iterator.prototype.forEach()Array.prototype.forEach()
Iterator.prototype.map()Array.prototype.map()
Iterator.prototype.reduce()Array.prototype.reduce()
Iterator.prototype.some()Array.prototype.some()

Iterator.prototype.drop() andIterator.prototype.take() combined are somewhat analogous toArray.prototype.slice().

Iterator helper objects

Note:Iterator helper objects anditerator helper methods are two different concepts. An Iterator helper object is detectable at runtime, while "iterator helper method" is just a name for a set of methods for comprehension.Iterator helper may refer to either the object or the method, depending on the context.

Among the iterator helper methods,filter(),flatMap(),map(),drop(), andtake() return a newIterator Helper object. The iterator helper is also anIterator instance, making these helper methods chainable. All iterator helper objects inherit from a common prototype object, which implements the iterator protocol:

next()

Calls thenext() method of the underlying iterator, applies the helper method to the result, and returns the result.

return()

Calls thereturn() method of the underlying iterator, and returns the result.

The iterator helper shares the same data source as the underlying iterator, so iterating the iterator helper causes the underlying iterator to be iterated as well. There is no way to "fork" an iterator to allow it to be iterated multiple times.

js
const it = [1, 2, 3].values();const it2 = it.drop(0); // Essentially a copyconsole.log(it.next().value); // 1console.log(it2.next().value); // 2console.log(it.next().value); // 3

Proper iterators

There are two kinds of "iterators": objects that conform to theiterator protocol (which, at its minimum, only requires the presence of anext() method), and objects that inherit from theIterator class, which enjoy the helper methods. They do not entail each other — objects that inherit fromIterator do not automatically become iterators, because theIterator class does not define anext() method. Instead, the object needs to define anext() method itself. Aproper iterator is one that both conforms to the iterator protocol and inherits fromIterator, and most code expect iterators to be proper iterators and iterables to return proper iterators. To create proper iterators, define a class that extendsIterator, or use theIterator.from() method.

js
class MyIterator extends Iterator {  next() {    // …  }}const myIterator = Iterator.from({  next() {    // …  },});

Constructor

Iterator()

Intended to beextended by other classes that create iterators. Throws an error when constructed by itself.

Static methods

Iterator.from()

Creates a newIterator object from an iterator or iterable object.

Instance properties

These properties are defined onIterator.prototype and shared by allIterator instances.

Iterator.prototype.constructor

The constructor function that created the instance object. ForIterator instances, the initial value is theIterator constructor.

Iterator.prototype[Symbol.toStringTag]

The initial value of the[Symbol.toStringTag] property is the string"Iterator". This property is used inObject.prototype.toString().

Note:Unlike the[Symbol.toStringTag] on most built-in classes,Iterator.prototype[Symbol.toStringTag] is writable for web compatibility reasons.

Instance methods

Iterator.prototype.drop()

Returns a new iterator helper object that skips the given number of elements at the start of this iterator.

Iterator.prototype.every()

Tests whether all elements produced by the iterator pass the test implemented by the provided function.

Iterator.prototype.filter()

Returns a new iterator helper object that yields only those elements of the iterator for which the provided callback function returnstrue.

Iterator.prototype.find()

Returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function,undefined is returned.

Iterator.prototype.flatMap()

Returns a new iterator helper object that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable).

Iterator.prototype.forEach()

Executes a provided function once for each element produced by the iterator.

Iterator.prototype.map()

Returns a new iterator helper object that yields elements of the iterator, each transformed by a mapping function.

Iterator.prototype.reduce()

Executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value.

Iterator.prototype.some()

Tests whether at least one element in the iterator passes the test implemented by the provided function. It returns a boolean value.

Iterator.prototype.take()

Returns a new iterator helper object that yields the given number of elements in this iterator and then terminates.

Iterator.prototype.toArray()

Creates a newArray instance populated with the elements yielded from the iterator.

Iterator.prototype[Symbol.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 afor...of loop:

js
const arrIterator = [1, 2, 3].values();for (const value of arrIterator) {  console.log(value);}// Logs: 1, 2, 3

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-%iteratorprototype%-object

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp