JavaScript: Iterator

By Xah Lee. Date: . Last updated: .

New in ES2015.

An iterator object is any object with property key "next", and its value must be a function, and this function must return {done: boolean, value: value}.

iterator object can also have "return" and "throw" methods. The "return" method is called when the loop is exited, such as by break or return statement or a exception.

Here's a example of defining an iterable object.

let myIteratorObj = {
    i: 0,
    next: function () {
        return ( (this.i < 3) ? { value: this.i++, done: false } : { value: undefined, done: true } );
    }
};

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

for (let v of myIterableObj) {
  console.log(v);
}
// prints
// 0
// 1
// 2

To fully understand iterable, iterator, see JavaScript: Interface.

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.