JavaScript: Iterable

By Xah Lee. Date: . Last updated: .

New in JS2015.

Purpose of Iteratable

The purpose of Iteratable object is that they can be iterated over using for-of Loop , or, all items feed into array/argument items by using Spread Operator .

Also, a 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.

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. [see Symbol Tutorial]
  2. The Symbol is a function object. Symbol() returns a value that has type of 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 a symbol.)
  5. Objects can use the value of Symbol.iterator as a property key. For example, obj_name[Symbol.iterator] = ….
  6. Any object that has a property symbol of Symbol.iterator is called β€œiterable”.
  7. The value of obj_name[Symbol.iterator] must be a function that returns a iterator. [see Iterator]
); // true

(typeof Symbol.iterator) === "symbol"
); // true

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

// array instance has inherited property key Symbol.iterator

const aa = [3,4,5];

console.log( Symbol.iterator in aa ); // true

// not its own property
! aa.hasOwnProperty(Symbol.iterator)
); // true

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

Reflect.apply (
); // true

Standard Iterable Objects

Standard builtin objects that are iterables include:

[String, Array, Set, Map]
.every (x => (typeof x.prototype[Symbol.iterator] === "function" ))
// 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. [see Generator Function]

test if a object is iterable

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

const x1 = [3,4,5];
console.log(Reflect.has(x1, Symbol.iterator)); // true

const x2 = { a: 3, b: 4 };
console.log(Reflect.has(x2, Symbol.iterator)); // false

JavaScript Iterable 🌟

JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types





Object and Inheritance



Iterable 🌟