JS: Iterable

By Xah Lee. Date: . Last updated: .

New in ES2015.

Iterable Object

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

Here's what it means:

  1. Symbol is a new type of value in ES2015. [see JS: Symbol Tutorial]
  2. The Symbol is a function object. Symbol() returns a value that is 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 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 JS: Iterator]
console.log(
Symbol.hasOwnProperty("iterator")
) // true

console.log(
Symbol.iterator
) // Symbol(Symbol.iterator)

console.log(
(typeof Symbol.iterator) === "symbol"
) // true

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

// array instance has property Symbol.iterator, but is inherited

let aa = [3,4,5];

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

// is not its own property
console.log( aa.hasOwnProperty(Symbol.iterator) ) // false

// the property symbol Symbol.iterator of array is inherited
console.log ( Symbol.iterator in Reflect.getPrototypeOf ( aa ) ); // 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.

[see JS: Interface]

Standard Iterable Objects

Standard builtin objects that are iterables include:

console.log ( Reflect.has ( String.prototype , Symbol.iterator ) ); // true
console.log ( Reflect.has ( Array.prototype , Symbol.iterator ) ); // true
console.log ( Reflect.has ( Set.prototype , Symbol.iterator ) ); // true
console.log ( Reflect.has ( Map.prototype , Symbol.iterator ) ); // true

Purpose of Iteratable

The purpose of Iteratable object is that they can be iterated over using for-of loop.

The for-of loop (from ES2015) is designed so that it can go over data structure properly. For example, has definite order, without going up the prototype chain, and without relying on property index or converting to array.

Iterate by For-Of Loop

The for-of loop syntax can be used on any iterable object.

[see JS: for-of Loop]

Define Your Own Iterable Object

You can easily create your own iterable object using Generator Function. [see JS: Generator Function]

Iterable / Iterator / Generator Topic

  1. JS: Interface
  2. JS: Iterable
  3. JS: Iterator
  4. JS: for-of Loop
  5. JS: Generator Function
  6. JS: Generator
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon