loading...

Iterators

mohananagavenkat profile image Mohana Naga Venkat Sayempu ・1 min read

es6 (9 Part Series)

1) let and const in javascript 2) Arrow Functions 3 ... 7 3) ES6 Modules 4) Template Strings 5) Object Literal Enhancements 6) Destructuring 7) Spread Operator 8) Symbols 9) 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
      }
    }
  }
}

es6 (9 Part Series)

1) let and const in javascript 2) Arrow Functions 3 ... 7 3) ES6 Modules 4) Template Strings 5) Object Literal Enhancements 6) Destructuring 7) Spread Operator 8) Symbols 9) Iterators

Posted on May 27 by:

mohananagavenkat profile

Mohana Naga Venkat Sayempu

@mohananagavenkat

Full-Stack Developer. In a relationship with web 😁. Worked for startup companies. Apart from that, I am a good Badminton Player.

Discussion

markdown guide