JS: Iterable Object

By Xah Lee. Date: . Last updated: .

New in JS2015.

What is Iteratable Object

An iterable object holds special values to be iterated over.

An iterable object can have potentially infinite number of items, computed at the time when needed. As opposed to a array, where every item already exists and occupy memory.

Example of Iterable's Values

Iterated values can anything the iteratable object is designed for, such a list of prime numbers.

How to Iterate Over Iterable's Values

Technical Definition of Iterable Object

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

The value of obj_name[Symbol.iterator] must be a function that returns a Iterator.

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
console.log(
  aa.hasOwnProperty(Symbol.iterator) === false,
);

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

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

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

console.log(
  is_iterable(String.prototype),
  is_iterable(Array.prototype),
  is_iterable(Set.prototype),
  is_iterable(Map.prototype),
);

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