JavaScript: Iterable

By Xah Lee. Date: . Last updated: .

New in ES2015.

Iterable Object

An object with a Symbol.iterator method (own property or inherited) is called “iterable”.

Here's what it means:

  1. Symbol is a new data type value in ES2015. 〔►see JavaScript: Symbol Tutorial
  2. The Symbol is a function object. It creates symbol values. That is, 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” (aka “iterable object”).
  7. The value of obj_name[Symbol.iterator] must be a function that returns a iterator object. 〔►see JavaScript: 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

var 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.

JavaScript: Interface

List of Iterable Objects

Standard objects that have Symbol.iterator (own or inherited) as properties 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

Iterate by For-Of Loop

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

JavaScript: for-of Loop

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.