Path: blob/main/files/en-us/web/javascript/reference/iteration_protocols/index.md
6520 views
------{{jsSidebar("More")}}
Iteration protocols aren't new built-ins or syntax, but protocols. These protocols can be implemented by any object by following some conventions.
There are two protocols: The iterable protocol and the iterator protocol.
The iterable protocol
The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a {{jsxref("Statements/for...of", "for...of")}} construct. Some built-in types are built-in iterables with a default iteration behavior, such as {{jsxref("Array")}} or {{jsxref("Map")}}, while other types (such as {{jsxref("Object")}}) are not.
In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant {{jsxref("Symbol.iterator")}}:
[Symbol.iterator]: A zero-argument function that returns an object, conforming to the iterator protocol.
Whenever an object needs to be iterated (such as at the beginning of a {{jsxref("Statements/for...of", "for...of")}} loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.
Note that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the this keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.
This function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using yield.
The iterator protocol
The iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.
An object is an iterator when it implements a next() method with the following semantics:
next(): A function that accepts zero or one argument and returns an object conforming to the
IteratorResultinterface (see below). If a non-object value gets returned (such asfalseorundefined) when a built-in language feature (such asfor...of) is using the iterator, a {{jsxref("TypeError")}} ("iterator.next() returned a non-object value") will be thrown.
All iterator protocol methods (next(), return(), and throw()) are expected to return an object implementing the IteratorResult interface. It must have the following properties:
done{{optional_inline}}: A boolean that's
falseif the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying thedoneproperty altogether.)Has the value
trueif the iterator has completed its sequence. In this case,valueoptionally specifies the return value of the iterator.
value{{optional_inline}}: Any JavaScript value returned by the iterator. Can be omitted when
doneistrue.
In practice, neither property is strictly required; if an object without either property is returned, it's effectively equivalent to { done: false, value: undefined }.
If an iterator returns a result with done: true, any subsequent calls to next() are expected to return done: true as well, although this is not enforced on the language level.
The next method can receive a value which will be made available to the method body. No built-in language feature will pass any value. The value passed to the next method of generators will become the value of the corresponding yield expression.
Optionally, the iterator can also implement the return(value) and throw(exception) methods, which, when called, tells the iterator that the caller is done with iterating it and can perform any necessary cleanup (such as closing database connection).
return(value){{optional_inline}}: A function that accepts zero or one argument and returns an object conforming to the
IteratorResultinterface, typically withvalueequal to thevaluepassed in anddoneequal totrue. Calling this method tells the iterator that the caller does not intend to make any morenext()calls and can perform any cleanup actions.
throw(exception){{optional_inline}}: A function that accepts zero or one argument and returns an object conforming to the
IteratorResultinterface, typically withdoneequal totrue. Calling this method tells the iterator that the caller detects an error condition, andexceptionis typically an {{jsxref("Error")}} instance.
Note: It is not possible to know reflectively (i.e. without actually calling
next()and validating the returned result) whether a particular object implements the iterator protocol.
It is very easy to make an iterator also iterable: just implement an [@@iterator]() method that returns this.
Such object is called an iterable iterator. Doing so allows an iterator to be consumed by the various syntaxes expecting iterables — therefore, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. (In fact, almost all syntaxes and APIs expect iterables, not iterators.) The generator object is an example:
However, when possible, it's better for iterable[Symbol.iterator] to return different iterators that always start from the beginning, like Set.prototype[@@iterator]() does.
The async iterator and async iterable protocols
There are another pair of protocols used for async iteration, named async iterator and async iterable protocols. They have very similar interfaces compared to the iterable and iterator protocols, except that each return value from the calls to the iterator methods is wrapped in a promise.
An object implements the async iterable protocol when it implements the following methods:
: A zero-argument function that returns an object, conforming to the async iterator protocol.
An object implements the async iterator protocol when it implements the following methods:
next(): A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the
IteratorResultinterface, and the properties have the same semantics as those of the sync iterator's.
return(value){{optional_inline}}: A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the
IteratorResultinterface, and the properties have the same semantics as those of the sync iterator's.
throw(exception){{optional_inline}}: A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the
IteratorResultinterface, and the properties have the same semantics as those of the sync iterator's.
Interactions between the language and iteration protocols
The language specifies APIs that either produce or consume iterables and iterators.
Built-in iterables
{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, and Segments (returned by Intl.Segmenter.prototype.segment()) are all built-in iterables, because each of their prototype objects implements an @@iterator method. In addition, the arguments object and some DOM collection types such as {{domxref("NodeList")}} are also iterables. ReadableStream is the only built-in async iterable at the time of writing.
Generator functions return generator objects, which are iterable iterators. Async generator functions return async generator objects, which are async iterable iterators.
The iterators returned from built-in iterables actually all inherit from a common class (currently unexposed), which implements the aforementioned [Symbol.iterator]() { return this; } method, making them all iterable iterators. In the future, these built-in iterators may have additional helper methods in addition to the next() method required by the iterator protocol. You can inspect an iterator's prototype chain by logging it in a graphical console.
Built-in APIs accepting iterables
There are many APIs that accept iterables. Some examples include:
{{jsxref("Map/Map", "Map()")}}
{{jsxref("WeakMap/WeakMap", "WeakMap()")}}
{{jsxref("Set/Set", "Set()")}}
{{jsxref("WeakSet/WeakSet", "WeakSet()")}}
{{jsxref("Promise.all()")}}
{{jsxref("Promise.allSettled()")}}
{{jsxref("Promise.race()")}}
{{jsxref("Promise.any()")}}
{{jsxref("Array.from()")}}
Syntaxes expecting iterables
Some statements and expressions expect iterables, for example the {{jsxref("Statements/for...of", "for...of")}} loops, array and parameter spreading, {{jsxref("Operators/yield*", "yield*")}}, and array destructuring:
When built-in syntaxes are iterating an iterator, and the last result's done is false (i.e. the iterator is able to produce more values) but no more values are needed, the return method will get called if present. This can happen, for example, if a break or return is encountered in a for...of loop, or if all identifiers are already bound in an array destructuring.
The for await...of loop and yield* in async generator functions (but not sync generator functions) are the only ways to interact with async iterables. Using for...of, array spreading, etc. on an async iterable that's not also a sync iterable (i.e. it has [@@asyncIterator]() but no [@@iterator]()) will throw a TypeError: x is not iterable.
Non-well-formed iterables
If an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable.
Using one is likely to result in runtime errors or buggy behavior:
Examples
User-defined iterables
You can make your own iterables like this:
Simple iterator
Iterators are stateful by nature. If you don't define it as a generator function (as the example above shows), you would likely want to encapsulate the state in a closure.
Infinite iterator
Defining an iterable with a generator
Defining an iterable with a class
State encapsulation can be done with private properties as well.
Overriding built-in iterables
For example, a {{jsxref("String")}} is a built-in iterable object:
String's default iterator returns the string's code points one by one:
You can redefine the iteration behavior by supplying our own @@iterator:
Notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol: