Search notes:

JavaScript: iterator and iterable

In order to be able to iterate over an object in JavaScript, two specific so-called protocols must be implemented: the iterable and the iterator protocol.
The iterable protocol requires an object to define an @@iterator ([Symbol.iterator]) method which returns an iterator object.
The iterator protocol requires this returned iterator object to define at least a next() method that returns an object that has at least the two properties value and done. As long as done evaluates to true, the iterating mechanism will call next().
The following snippet of code is an attempt to demonstrate the iterator and iterable protocol:
let iterator = {
   vals  :['one', 'two', 'three', 'four', 'five'],
   cur   : 0 ,
   next: function() {
      return {
        value: this.vals[this.cur],
        done : this.cur ++ >= this.vals.length
      }
   }
};

let iterable = {
   [Symbol.iterator]: function() {
      return iterator;
   }
};

for (let num of iterable) {
   print(num);
}
Github repository about-javascript, path: /statements/iteration/iterator-iterable.js

Index