JavaScript: Iterator

By Xah Lee. Date: . Last updated: .

New in JS2015.

What is 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 .

Purpose of Iterator

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

Defining an Iterator

Here is a example of defining an iterator.

// create a iterator

const itor = {};

itor.i = 0;

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

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

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

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

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

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

Defining a Iterable with Given Iterator

Here is a example of defining a iterable from a iterator.

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

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

// --------------------------------------------------
// spread operator test on iterable
console.log(...xRable);
// 0 1 2

Inherited Key β€œnext”

Here is 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 xRable = { [Symbol.iterator]: (() => x2) };

// --------------------------------------------------
// spread operator test on iterable
console.log(...xRable);
// 0 1 2

JavaScript Iterable 🌟

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc