The Iterable Protocol

Learn how to implement the iterable protocol.

We'll cover the following

The iterable protocol defines a standardized means for an object to return an iterator. Such objects are called iterables. Usually, an iterable is a container of elements, such as a data structure, but it can also be an object virtually representing a set of elements, such as a Directory object, which would allow us to iterate over the files in a directory.

In JavaScript, we can define an iterable by making sure it implements the @@iterator method, or in other words, a method accessible through the built-in symbol Symbol.iterator.

Note: The @@name convention indicates a well-known symbol according to the ES6 specification.

Such an @@iterator method should return an iterator object, which can be used to iterate over the elements represented by the iterable. For example, if our iterable is a class, we would have something like the following:

Get hands-on with 1400+ tech skills courses.