Iterator Built-Ins

Learn about different constructs and built-in APIs supporting iterables.

Iterators and iterables as a native JavaScript interface

At this point, you may ask: “What’s the point of having all these protocols for defining iterators and iterables?” Well, having a standardized interface allows third-party code as well as the language itself to be modeled around the two protocols we’ve just seen. This way, we can have APIs (even native) as well as syntax constructs accepting iterables as input.

  For example, the most obvious syntax construct accepting an iterable is the for...of loop. We’ve just seen in the last code sample that iterating over a JavaScript iterator is a really standard operation, and its code is mostly boilerplate. In fact, we’ll always have an invocation to next() to retrieve the next element and a check to verify if the done property of the iteration result is set to true, which indicates the end of the iteration. But, don’t worry, simply pass an iterable to the for...of instruction to seamlessly loop over the elements returned by its iterator. This allows us to process the iteration with an intuitive and compact syntax.

Get hands-on with 1200+ tech skills courses.