JS: Iterable Object

By Xah Lee. Date: . Last updated: .

New in JS2015.

Purpose of Iteratable Object

What is Iterable Object

A iterable object is an object that has (own or inherited) property Symbol.iterator.

In practice, it just means you can use for-of Loop or Spread Operator or Array.from on it.

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. e.g. 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.

  (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));

// not its own property
  aa.hasOwnProperty(Symbol.iterator) === false,

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


Test If Object is Iterable

Standard Iterable Objects

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

const is_iterable = ((x) => (Reflect.has(x, Symbol.iterator)));


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