JS: Iterator

By Xah Lee. Date: . Last updated: .

New in ES2015.

What's Iterator

An iterator object is any object with property key "next" (own property or inherited), 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 myIterator = {
    i: 0,
    next: function () {
        return ( (this.i < 3) ? { value: this.i++, done: false } : { value: undefined, done: true } );
    }
};

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

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

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

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

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

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

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

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

Inherited Key “next”

Here's an example showing a iterator with inherited key "next".

// check iterator has key "next" that's not its own

const et = ["a", "b", "c"].entries();

// is iterator
console.log (
 Object.prototype.toString .call (et) === "[object Array Iterator]"
); // true

// has key "next" in proto chain
console.log (
"next" in et
); // true

// not its own
console.log (
et.hasOwnProperty ( "next" ) === false
); // true

// in parent
console.log (
  ( Reflect.getPrototypeOf ( et ) ). hasOwnProperty ( "next" )
); // true

Purpose

The purpose of iterator is that they are functions required as property value of iterable objects.

[see JS: Interface]

Any function or operator that works with iterable objects, rely on iterator function in the iterable object. For example, [see JS: for-of Loop]

In everyday coding, it's not necessary to understand what iterator object is.

JS Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog