The Spread Operator and Non-Array Iterables

Recall from Chapter 7 that the spread operator (...) can be used to convert a set into an array. For example:

  1. let set = new Set([1, 2, 3, 3, 3, 4, 5]),
  2. array = [...set];
  3. console.log(array); // [1,2,3,4,5]

This code uses the spread operator inside an array literal to fill in that array with the values from set. The spread operator works on all iterables and uses the default iterator to determine which values to include. All values are read from the iterator and inserted into the array in the order in which values were returned from the iterator. This example works because sets are iterables, but it can work equally well on any iterable. Here’s another example:

  1. let map = new Map([ ["name", "Nicholas"], ["age", 25]]),
  2. array = [...map];
  3. console.log(array); // [ ["name", "Nicholas"], ["age", 25]]

Here, the spread operator converts map into an array of arrays. Since the default iterator for maps returns key-value pairs, the resulting array looks like the array that was passed during the new Map() call.

You can use the spread operator in an array literal as many times as you want, and you can use it wherever you want to insert multiple items from an iterable. Those items will just appear in order in the new array at the location of the spread operator. For example:

  1. let smallNumbers = [1, 2, 3],
  2. bigNumbers = [100, 101, 102],
  3. allNumbers = [0, ...smallNumbers, ...bigNumbers];
  4. console.log(allNumbers.length); // 7
  5. console.log(allNumbers); // [0, 1, 2, 3, 100, 101, 102]

The spread operator is used to create allNumbers from the values in smallNumbers and bigNumbers. The values are placed in allNumbers in the same order the arrays are added when allNumbers is created: 0 is first, followed by the values from smallNumbers, followed by the values from bigNumbers. The original arrays are unchanged, though, as their values have just been copied into allNumbers.

Since the spread operator can be used on any iterable, it’s the easiest way to convert an iterable into an array. You can convert strings into arrays of characters (not code units) and NodeList objects in the browser into arrays of nodes.

Now that you understand the basics of how iterators work, including for-of and the spread operator, it’s time to look at some more complex uses of iterators.