JavaScript: Iterable Object

By Xah Lee. Date: . Last updated: .

New in JS2015.

Purpose of Iteratable Object

What is Iterable Object

A iterable object is basically any object with a Symbol.iterator method (own property or inherited).

Here is what it means:

  1. Symbol is a new type of value in JS2015.
  2. The Symbol is a function object. Symbol() returns a value of type symbol.
  3. The function object Symbol has many properties.
  4. One of Symbol's property key is "iterator", and its value is a symbol. (that is, the type of Symbol.iterator is symbol.)
  5. Objects can use the value of Symbol.iterator as a property key. For example, obj_name[Symbol.iterator] = ….
  6. The value of obj_name[Symbol.iterator] must be a function that returns a Iterator.
  7. Any object that has a property key of Symbol.iterator is called β€œiterable”.
console.log(
  Symbol.hasOwnProperty("iterator"),
);

console.log(
  (typeof Symbol.iterator) === "symbol",
);

For example, array is iterable object. Because it has inherited property key Symbol.iterator.

const aa = [3, 4, 5];

// array has an inherited property key Symbol.iterator
console.log(Reflect.has(aa, Symbol.iterator) === true);

// not its own property
console.log(
  !aa.hasOwnProperty(Symbol.iterator) === true,
);

// the property Symbol.iterator of array is inherited from Array.prototype

console.log(
  Reflect.apply(
    Object.prototype.hasOwnProperty,
    Array.prototype,
    [Symbol.iterator],
  ) === true,
);

test if a object is iterable

To test if something is iterable, check for the existence of property Symbol.iterator, using Reflect.has

// array is iterable
const aa = [3, 4, 5];
console.log(Reflect.has(aa, Symbol.iterator));

Standard Iterable Objects

Standard objects that are iterables include: String, Array, Set, Map.

console.log(
  [String, Array, Set, Map]
    .every((x) => Reflect.has(x.prototype, Symbol.iterator)) === true,
);

The Iterable Interface

Technically, any object that conforms to the Iterable Interface is called Iterable. To fully understand iterable, you need to understand JavaScript Interface.

Define Your Own Iterable Object

You can easily create your own iterable object using Generator Function .

JavaScript Iterable 🌟

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc