JS: 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}.

Technically, we say that the object conforms to the iterator interface.

〔►see JS: Interface

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 iterator.

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

console.log ( myIteratorObj.next() );
// { value: 0, done: false }

console.log ( myIteratorObj.next() );
// { value: 1, done: false }

console.log ( myIteratorObj.next() );
// { value: 2, done: false }

console.log ( myIteratorObj.next() );
// { value: undefined, done: true }

Here's a example of defining an iterator and iterable.

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

Iterable / Iterator / Generator Topic

  1. JS: Interface
  2. JS: Iterable
  3. JS: Iterator
  4. JS: for-of Loop
  5. JS: Generator Function
  6. JS: Generator
Like what you read? Buy JavaScript in Depth