Today we will see how useful is spread operator in ECMA6, so without wasting any much of time let’s begin the session.
Copying array/object without reference
If we copy an array to a different variable like shown below we see that not only value but actually the reference of the array is also copied, which results in the behavior where we make a change in the copied array but the actual array also gets changed.
let arr= ['a','b','c','d']; let newArr= arr;
Now in ES6, we can perform the same thing without copying the reference as shown below, here you can see that changes made to a2 do not reflect in arr
Similarly, you can copy an object without reference as shown below
With ES6 it becomes very easy now to insert an array within another array which was difficult before ES6. In the below code we are inserting array arr in the middle of new array newArr, with the output as [“a”, “b”, “c”, “d”, “e”], check the result tab below
Similar to array, we can also insert an object to another object
We can merge 2 or more array to a single array or even 2 or more objects to a single object. Here is how the spread operator helps us to achieve it.
Eliminate duplicates from an Array
Remember how difficult it took us to remove duplicates from an array earlier, but thanks to the spread operator it’s just a single line of code which does the work for us
Converting String to Array
Before spread operators, if you remember we were using split() method to convert our strings to an array and now see how we can use the spread operator. In below snippet, you can see that our string str is converted to an array of characters
Converting String to Object
As we just saw spread operator helped us to convert a string to an array, similarly we can also convert a string to an object, look below code snippet and don’t forget to switch to Result tab
Using Math functions
We can now easily use Math min() and max() function to get the smallest and largest number in an array. We can even search the smallest or largest number of more than 1 array.
An array of N numbers
What if we want to create a new array of numbers containing prepopulated 1st N numbers. So simple with spread operator and keys() method, here it goes,