Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array. Syntax of Spread operator is same as Rest parameter but it works completely opposite of it.
var variablename1 = [...value];
In the above syntax, … is spread operator which will target all values in particular variable. When … occurs in function call or alike,its called a spread operator. Spread operator can be used in many cases,like when we want to expand,copy,concat,with math object. Let’s look at each of them one by one:
Note: In order to run the code in this article make use of the console provided by the browser.
We can achieve the same output with the help of the spread operator, the code will look something like this:
Note: Though we can achieve the same result, but it is not recommended to use the spread in this particular case, as for a large data set it will work slower as when compared to the native concat() method.
Copy(like splice method)
In order to copy the content of array to another we can do something like this:
The above code works fine because we can copy the contents of one array to another, but under the hood, it’s very different as when we mutate new array it will also affect the old array(the one which we copied). See the code below:
In the above code we can clearly see that when we tried to insert an element inside the array, the original array is also altered which we didn’t intended and is not recommended. We can make use of the spread operator in this case, like this:
By using the spread operator we made sure that the original array is not affected whenever we alter the new array.
Whenever we want to expand an array into another we do something like this:
Even though we get the content on one array inside the other one, but actually it is array inside another array which is definitely what we didn’t want. If we want the content to be inside a single array we can make use of the spread operator.
Now consider that we have an array instead of a list, this above Math object method won’t work and will return NaN, like:
When …arr is used in the function call, it “expands” an iterable object arr into the list of arguments
In order to avoid this NaN output, we make use of spread operator, like:
Example of spread operator with objects
Here we are spreading the user1 object. All key-value pairs of the user1 object are copied into the clonedUser object. Let’s look on another example of merging two objects using the spread operator,
mergedUsers is a copy of user1 and user2. Actually, every enumerable property on the objects will be copied to mergedUsers object. The spread operator is just a shorthand for the Object.assign() method but, they are some differences between the two.