JS: Iterable

By Xah Lee. Date: . Last updated: .

New in ES2015.

Purpose of Iteratable

The purpose of Iteratable object is that they can be iterated over using for-of loop, or, all items listed by using Spread Operator (... iterable) .

Also, a iterable object can have potentially infinite number of items. As opposed to a array or map or set, which every item occupy memory.

The for-of loop 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.

What is 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 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 JS: Iterator]
console.log (
Symbol.hasOwnProperty("iterator")
); // true

console.log(
(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
console.log (
! aa.hasOwnProperty(Symbol.iterator)
); // true

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

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

Standard Iterable Objects

Standard builtin objects that are iterables include:

console.log (
[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.

[see JS: Interface]

Define Your Own Iterable Object

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

JS Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials