Iterators
The existence of [Symbol.iterator]
property in an object makes it iterable.
An iterable object:
- can be looped with the
for-of
loop - can be spread into an array using the
...
operator, e.g.[...iterable]
The [Symbol.iterator]
property
The [Symbol.iterator]
property is a method that when called returns an iterator.
(Note that it is a property that uses Symbol.iterator
as its name. Symbol.iterator
is a special Symbol defined by JavaScript.)
Iterator
An iterator is any object that has the next()
method.
Iteration result
Calling next()
in an iterator returns an iteration result object. An iteration result object is an object containing the following properties:
value
(required, any value) — the item being iterated (e.g. the element of an array; key-value pair of a Map).done
(required, boolean) —true
if all items have been iterated;false
otherwise.
You can keep calling next
until you get iteration result object whose done
value is true
.
Example: the Range
object
References
- JavaScript: The Definitive Guide, 7th Edition (David Flanagan) — Chapter 12. Iterators and Generators