ES6 – Iterator protocol

Hi, in this post I’m going to show you the new iteration protocols of ES6 one is the “iterable protocol” and the other is “iterator protocol

First that all let me explain that a “Iterator protocol” is a set of rules that an object needs to follow for implement the interface, which when used, a loop or a constructor can iterate over a group of values of that object.

ES6 – Iterator protocol

An object that implement the iterator protocol is know as iterator. In this protocol an object need to provide a next() method that returns the next item in the sequence of a group of items.

let myObject = {
  data: [100, 200, 300, 400, 500],
  nextIndex: 0,
  next: function () {
    return this.nextIndex < this.data.length
      ? { value: this.data[this.nextIndex++], done: false }
      : { done: true };
  },
};

console.log("value --->", myObject.next().value); // 100
console.log("value --->", myObject.next().value); // 200
console.log("value --->", myObject.next().value); // 300
console.log("value --->", myObject.next().value); // 400
console.log("value --->", myObject.next().value); // 500
console.log("value --->", myObject.next().done); // true

Result:

So in this case, every time that we call the next() method it will return an object with 2 properties: value and done.

Value property:

Value will hold the value of the current item in the collection and it is omitted when the done property is true.

Done property:

This property return true if the iterator has finished iterating over the collection of values. Otherwise will return false.

By Cristina Rojas.