sajad torkamani

Iterable protocol

The iterable protocols allows JavaScript objects to define or customise their iteration behaviour (i.e., what values are looped over in a for..of construct.)

Some built-in types (e.g., Array or Map) are built-in iterables, while other types (e.g., Object) are not.

In order to be iterable, an object must implement the @@iterator method, meaning that the object or one of the objects in its prototype chain must have a @@iterator key that’s available via the constant Symbol.iterator.

Whenever an object needs to be iterated, its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

Iterator protocol

The iterator protocol defines a standard way to produce a sequence of values (finite or infinite), and potentially a return value when all values have been generated.

We say an object is an iterator when it implements a next() method: which is a zero arg function that returns an object with atleast the following two properties:

  • done (boolean): Set to true if the iterator is past the end of the iterated sequence. In this case, value optionally specifies the return value of the iterator.
  • value (any): Any JavaScript value returned by the iterator. Can be omitted when done is true.

If next() returns a non-object value, a TypeError will be thrown with the message iterator.next() returnd a non-object value.

Sources/links

Tagged: JavaScript

Leave a comment

Your email address will not be published. Required fields are marked *