Explain spread operator in ES6 with an Example
In this article, we will try to understand the basic details which are associated with the Spread operator which includes the syntax of the spread operator and its usage with the help of certain examples in ES6.
Let us first understand what is exactly Spread Operator is and what is its syntax and then further we will see some examples associated with its declaration.
- The spread operator eventually takes any iterable object such as an array or any other iterable object and expands the values of that iterable object individually.
- This spread operator is mainly used with the array containing more than 1 value in it.
- That is, it basically spreads out all the elements of an array, and further after spreading the array elements we could perform any operations with those elements like concatenation, copying the elements of an array into another array, and so on.
- Spread operator can also be used with objects for several operations like concatenation or copying one object’s values into another object and so on.
Syntax: Following syntax, we may use to implement spread operator with any iterable object like an array.
let variable = [...values];
Basically, what this syntax is doing that is taking the values from an array and thus storing it in a variable which is therefore acting as an array itself.
Now that we have understood the basics of the Spread operator including its syntax, it’s high time to see few examples which are based on the usage of the spread operator.
Example 1: In this example, we will try to perform the concatenation by firstly using the concat() method and then by using the simpler way which is by using the spread operator.
Output: As you can see in the above code snippet that it becomes so simple to perform concatenation by using the spread operator syntax instead of using the predefined method concat().
[ 5, 6, 7, 8, 9, 10 ] [ 5, 6, 7, 8, 9, 10 ]
Example 2: In this example, we will try to copy the values of one array into another array then afterward we will try to add some more values into the new array and then further we will see the changes being impacted on the previous and new array elements.
Output: As you can see in the above example when we normally entered a new value in the new array it doesn’t impact the older array, if we try to do it with the regular method we might get new array elements as same as older array elements.
[ 'Apple', 'Mango', 'Banana' ] [ 'Apple', 'Mango', 'Banana', 'Grapes' ] [ 'Apple', 'Mango', 'Banana' ]
Example 3: In this example, we will try to find the minimum element in an array of elements using the spread operator.
Output: If we try to find the minimum element using some simpler way then we might experience an error message which says NaN (Not a number), but with the use of a spread operator, we will not be getting any error message like this.