JavaScript: Iterator

By Xah Lee. Date: . Last updated: .

New in JS2015.

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

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 Iterator is a object that conforms to the iterator Interface .

Here's a example of defining an iterator.

// create an iterator

const rr = {};

rr.i = 0;

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

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

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

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

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

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

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

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

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

// --------------------------------------------------
// 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

JavaScript Iterable 🌟

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc