DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

Iterators

In ES6 objects are said to be iterable when they implement the iterable interface. Many built-in objects such as arrays, sets and maps implement this interface. User defined objects and classes can also implement the interface.

Iterable objects can also be iterated using the new for of loop, and used with the ... spread operator.

Iterable Interface

An object is said to conform to the iterable interface when the value of its property identified with the shared @@iterator Symbol is a function which returns an iterator.

var iterator = [1,2,3][Symbol.iterator]();

An iterator is any object that implements a next function.

var iterator = [1,2,3][Symbol.iterator]();

console.log(iterator.next); // '[Function]'

The next function can be called repeatedly to step through the iteration. Each time it returns an object that contains two keys, value and done. The values of these keys indicate the current value of the iteration and its completion status respectively.

var iterator = [1,2,3][Symbol.iterator]();

console.log(iterator.next()); // {value:1, done:false}
console.log(iterator.next()); // {value:2, done:false}
console.log(iterator.next()); // {value:3, done:false}
console.log(iterator.next()); // {value:undefined, done:true}

Custom objects and classes can be made iterable by implementing the iterator interface manually.

var iterable = {
  [Symbol.iterator] () {
    return {
      next () {
        // Implement iterator
      }
    }
  }
}

Top comments (0)