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.
var variablename1 = [...value];
The three dots (...) in the above syntax are the spread operator, which targets the entire values in the particular variable.
Let us try to understand the usage of spread operator in different cases:
Here, we are going to see how we can manipulate an array by using the spread operator.
When we construct an array using the literal form, the spread operator allows us to insert another array within an initialized array.
let colors = ['Red', 'Yellow']; let newColors = [...colors, 'Violet', 'Orange', 'Green']; console.log(newColors);
Spread operator can also be used to concatenate two or more arrays.
let colors = ['Red', 'Yellow']; let newColors = [...colors, 'Violet', 'Orange', 'Green']; console.log(newColors);
We can also copy the instance of an array by using the spread operator.
let colors = ['Red', 'Yellow']; let newColors = [...colors]; console.log(newColors);
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.
Let's understand the illustration for the same.
let colors = ['Red', 'Yellow']; let newColors = colors; newColors.push('Green'); console.log(newColors); console.log(colors);
let colors = ['Red', 'Yellow']; let newColors = [...colors]; newColors.push('Green'); console.log(newColors); console.log(colors);
Let's see how the spread operator spreads the strings. The illustration for the same is given below.
Here, we have constructed an array str from individual strings.
let str = ['A', ...'EIO', 'U']; console.log(str);
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.