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:
let set = new Set([1, 2, 3, 3, 3, 4, 5]),
array = [...set];
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:
let map = new Map([ ["name", "Nicholas"], ["age", 25]]),
array = [...map];
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:
let smallNumbers = [1, 2, 3],
bigNumbers = [100, 101, 102],
allNumbers = [0, ...smallNumbers, ...bigNumbers];
console.log(allNumbers.length); // 7
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.