The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of
construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array
or Map
, while other types (such as 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 Symbol.iterator
:
Whenever an object needs to be iterated (such as at the beginning of a 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
.