Lesson 23. Iterables

 

After reading lesson 23, you will

  • Know what an iterable is and how to use it
  • Know how to use the spread operator on iterables to ungroup an object’s items
  • Know how to use iterables in a for..in statement to loop over an object’s values
  • Know how to create your own iterables
  • Know how to customize the behavior of built-in iterables

JavaScript in ES2015 has introduced a couple of new protocols: the iterable protocol and the iterator protocol. Together these protocols describe the behavior and mechanics of objects that can be iterated—that is to say, objects that produce a series of values and can have their values looped over. When you think of objects that can be iterated, Array probably springs to mind, but you can also iterate Strings, the arguments object, NodeLists, and as we’ll see in the upcoming lessons, Sets and Maps. On top of having all these built-in iterables, you can, as you’ll discover in this lesson, build your own!

Consider this

The following code logs all of the indices of an array. But what if you wanted to log all of the values?

for (const i in array) {
  console.log(i);
}

23.1. Iterables—what are they?

An iterable is any object that follows the iterable protocol that’s new in JavaScript, introduced in ES2015.

23.2. The for..of statement

23.3. Spread

23.4. Iterators—looking under the hood of iterables

Summary