How to use the spread and rest operator
The aim of this article is to guide you on using the spread and rest operators, one of the advanced features introduced in ES6. The spread and rest operator allow us to spread out and combine multiple elements respectively. Both of them are denoted by 3 periods
.... Even though they might look the same, they work differently. While the spread operator expands an array, object, string or any other iterable, the rest parameter, however, does the exact opposite - it combines multiple elements together into an iterable.
How to use them?
Let’s see the use of the spread operator via some examples -
Here we have an array of fruits. It will print to the screen in this way:
and using the spread operator
the array is printed this way:
The spread operator expanded the contents of the array into individual elements. We can also create a copy of this array while adding new elements:
The spread operator thus has many uses.
The rest operator is used to combine multiple elements and is particularly useful during array and object destructuring.
In the example above, the first two elements from the array
people are destructured or broken down into 2 variables
lawyer respectively. The rest of the elements are combined into the
students variable in the form of an array with the help of the rest operator.
Here’s another example with an object:
Here, we take an object then break it down and assign it to separate variables and then combine the remaining object properties in a single object. Let’s print it out and see the result:
Where to use them?
We’ve seen how the spread and rest operators are used. We can use the spread operator to efficiently split arrays, objects, and strings. Splitting up a string into characters has become easier. Working with objects has become hassle-free. Be it copying, cloning or concatenating, the spread operator makes it easy to work with arrays and objects.
As for the rest operator, there is no longer any need to do all those complicated things like accessing the
arguments object when dealing with variable function arguments. Simply using the rest operator solves everything for us:
This works just fine since the rest operator combines all arguments passed to the function in an array. All we have to do is traverse through the array and we can access all the arguments.
The rest and spread operators, in my opinion, are one of the best features of ES6 along with Promises. They offer a lot of benefits to using them in addition to making the code more readable. If you haven’t used them yet, what are you waiting for?
Originally published at dev.to.