ES6 has introduced the three dots (
The Rest operator uses the same syntax but does the opposite of the Spread operator. It reduces or collects values into an array.
The best way to grasp the difference between the two operators is through some examples.
The Spread Operator & the
Let’s assume, you want to print the elements of the following array in the console:
You would call the
console.log.apply() method as follows:
That’s because using the
console.log() directly will print the array as a single object.
In ES6, the Spread oparator allows you to do the same but in a much readable way:
We spread the values of the
letters array and we print them, just like if we are doing something like:
Deep Copying an Array with the Spread Operator
We can use the Spread operator to copy an array into another. For example:
letters2 array is a deep copy of the
letters array which means we can change the
letters2 array without affecting the first array.
Concatenating Arrays with the Spread Operator
We can use the Spread operator to concatenate two or more arrays into one array. Since the Spread operator unpack an array when it’s applied to it we can do something like:
We simply extract the values of the
b arrays into the new
Using the Spread Operator for Passing function arguments
Let’s suppose, you have a function that expects many individual arguments. For example, let’s this one:
And we have those values that we want to print in some array:
Instead of referencing each array member and passing it as a single argument which is quite tedious:
We can simply use the Spread operator like the following:
Transforming a String into an Array with the Spread Operator
As we mentionned before, both the Spread and Rest operator uses the three dots syntax prepended at the name of the symbol.
In the previous section, we’ve seen various examples of the Spread operator which expands iterables into their elements. Now, let’s see the Rest operator by example.
Just like its name suggests, the Rest operator collects the rest or the remaining of elements into an array.
Let’s suppose, you want to define a function that could take a variable number of arguments. You would use the
arguments object is an array-like object, as such as you can not use Array methods with it. You also can not use with Arrow functions which are now very common between JS developers to define functions.
A better alternative is to use the Rest operator. For example: