Iterator Built-Ins
Explore how JavaScript's iterator and iterable protocols enable standardized iteration using for...of loops, spread syntax, and built-in APIs. Understand the use of these constructs in Node.js, including creating streams from iterables, to write cleaner asynchronous code.
We'll cover the following...
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 ...