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:

  1. const arr = [11,12,13];
  2. const itr = arr[Symbol.iterator]();
  3. itr.next(); // { value: 11, done: false }
  4. itr.next(); // { value: 12, done: false }
  5. itr.next(); // { value: 13, done: false }
  6. itr.next(); // { value: undefined, done: true }

Note that you can write custom iterators by defining obj[Symbol.iterator]() with the object definition.