ES6 Spread Operator
ES6 Spread Operator
ES6 introduced a new operator referred to as a spread operator, which consists of three
dots (...). It allows an iterable to expand in places where more than zero arguments are
expected. It gives us the privilege to obtain the parameters from an array.
Spread operator syntax is similar to the rest parameter, but it is entirely opposite of it.
Let's understand the syntax of the spread operator.
Syntax
The three dots (...) in the above syntax are the spread operator, which targets the entire
values in the particular variable.
Example
Output
Concatenating arrays
Spread operator can also be used to concatenate two or more arrays.
Example
Output
Copying an array
We can also copy the instance of an array by using the spread operator.
Example
Output
[ 'Red', 'Yellow' ]
If we copy the array elements without using the spread operator, then inserting a new
element to the copied array will affect the original array.
But if we are copying the array by using the spread operator, then inserting an element
in the copied array will not affect the original array.
Example
Output
Note: Instead of elements, the spread operator only copies the array itself to the new one. It
means that the operator can do a shallow copy instead of a deep copy.
In the above example, we have applied the spread operator to the string 'EIO'. It
spreads out each specific character of the 'EIO' string into individual characters.
We will get the following output after the execution of the above code.
Output