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's 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]
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: • StringArraySetMap

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.

Define Your Own Iterable Object

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

JavaScript Iterable 🌟

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc