ES6 – Iterable protocol

Hi, any object that implement the iterable protocol is known as an iterable.

An object need to provide the @@iterator method: must have the Symbol.iterator symbol as a property key.

The @@iterator method must return an iterator object.

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

let iterable = myObject[Symbol.iterator]();

console.log("value ---->", iterable.next().value);
console.log("value ---->", iterable.next().value);
console.log("value ---->", iterable.next().value);
console.log("value ---->", iterable.next().value);
console.log("value ---->", iterable.next().value);
console.log("done ---->", iterable.next().done);

Result:

By Cristina Rojas.