JS: Iterator

By Xah Lee. Date: . Last updated: .

New in ES2015.

Purpose of Iterator

Iterator object is required as the return value of the function of property key Symbol.iterator of a iterable object.

That is: a iterable object must have property key Symbol.iterator, and its value must be a function, and this function must return a Iterator object.

[see JS: Interface]

What's Iterator

An iterator object is any object with property key "next" (own 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.

// create an iterator

const itr = {};

itr.i = 0;

itr.next = (() => ( (itr.i < 3) ? { value: itr.i++, done: false } : { value: undefined, done: true } ));

// --------------------------------------------------
// test

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

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

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

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

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

// create a iterator
const xx = {};
xx.i = 0;
xx.next = (() => ( (xx.i < 3) ? { value: xx.i++, done: false } : { value: undefined, done: true } ));

// create a iterable
let yy = { [Symbol.iterator]: (() => xx) };

// --------------------------------------------------
// spread operator test on iterable
console.log ( [... yy] );
// [ 0, 1, 2 ]

Inherited Key “next”

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

// create a iterator
const x1 = {};
x1.i = 0;
x1.next = (() => ( (x1.i < 3) ? { value: x1.i++, done: false } : { value: undefined, done: true } ));

// x2's parent is x1. x2 is now also a iterator
const x2 = Object.create (x1);

// create a iterable, using x2
let yy = { [Symbol.iterator]: (() => x2) };

// --------------------------------------------------
// spread operator test on iterable
console.log ( [... yy] );
// [ 0, 1, 2 ]

JS Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function
Like it? Help me by telling your friends. Or, 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 Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog