JavaScript Iterables


Iterable objects are things you can go through using for..of.

In simple terms, iterables need to have the Symbol.iterator method for technical reasons.

Iterating Over a String

You can employ a for..of loop to go through the elements of a string:


Iterating Over an Array

To go through each item in an Array, you can employ a for..of loop.


JavaScript Iterators

The iterator protocol explains how to create a sequence of values from an object.

An item turns into an iterator when it has a next() method.

The next() function should provide an object with two properties:

  • data (the subsequent data)
  • completed (either true or false)
value The iterator's output value
(Can be skipped if 'done' is true)
done Returns true when the iterator has finished
false when the iterator has generated a new value.

Home Made Iterable

This sequence goes on endlessly: 10, 20, 30, 40, and so on. Whenever the next() function is invoked:

The issue with creating your own iterable:

It doesn't work with the JavaScript for..of command.

A JavaScript iterable is something that has a special thing called Symbol.iterator.

The Symbol.iterator is a special function. It gives you another function called next().

You can go through each item in an iterable using this code: for (const x of iterable) { }.

The for..of loop automatically triggers the Symbol.iterator method.

We can also accomplish this task manually.