JS: Iterable Interface

By Xah Lee. Date: . Last updated: .

Object having Iterable Interface is called Iterable Object.

Basically means, for an object to be an Iterable Object, it must have the property Symbol.iterator, own or inherited. And the value of Symbol.iterator is an Iterator Object.

When a Iterable Object is in iterating construct, such as for-of Loop, its Iterator Object's property β€œnext” (value is a function) is called to generate values.

Iterable interface properties

property key Symbol.iterator

Symbol.iterator is a Symbol.

  • Value must be a function.
  • This function's return value must be an object that conforms to the Iterator Interface.

Example

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

// array has an inherited property key Symbol.iterator
console.assert(
 Reflect.has([3, 4], Symbol.iterator),
);

// not its own property
console.assert(
 Object.hasOwn([3, 4], Symbol.iterator) === false,
);

// the property Symbol.iterator of array is inherited from Array.prototype
console.assert(
 Object.hasOwn(Array.prototype, Symbol.iterator),
);