15. Iterators
An iterator accesses the items from a collection one at a time, while keeping track of its current position within that sequence. It provides a next()
method which returns the next item in the sequence. This method returns an object with two properties: done and value.
ES6 has Symbol.iterator
which specifies the default iterator for an object. 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.
Let’s look at an array, which is an iterable, and the iterator it can produce to consume its values:
const arr = [11,12,13];
const itr = arr[Symbol.iterator]();
itr.next(); // { value: 11, done: false }
itr.next(); // { value: 12, done: false }
itr.next(); // { value: 13, done: false }
itr.next(); // { value: undefined, done: true }
Note that you can write custom iterators by defining obj[Symbol.iterator]()
with the object definition.