Hey Folks, Today I'll be talking about 3 Magical Dots i.e. Spread Operator in javascript that came with ES 6. This operator makes your job easier. Let's see this in action.
The first case could be copying one Array to another Array.
We can't simply copy an Array with an assignment operator as they are of type object, and objects in javascript are of reference type.
let arr1=[1,2,3];
let arr2=[...arr1];
This operator pulls out each element from arr1 and simplifies them to numbers, which then is wrapped by an [ ] array and assigned to arr2.
Before ES 6, slice() method was used to copy an array.
let arr1=[1,2,3];
let arr2=arr1.slice();
The second one could be copying one Object to another Object.
Now again, we can't copy an Object with an assignment operator as they are of reference type.
let obj1={prop1:val1, prop2:val2};
let obj2={...obj1};
Unsurprisingly, here too it pulls out each property: value pair from obj1 and simplifies them to individual property: value pair, which then is wrapped by an {} object and is assigned to obj2
Before ES 6, Object.assign() method was used to copy an object.
let obj1={prop1:val1, prop2:val2};
let obj2=Object.assign({}, obj1);
Using this Spread Operator we can also add/push new values into an array or an object.
let arr1=[1,2,3];
let arr2=[...arr1, 4];
This will add 4 to the new array arr2.
let obj1={prop1:val1, prop2:val2};
let obj2={...obj1, prop3:val3};
This will add prop3: val3 to the new object obj2.
Note: Now both the slice() method and spread operator return you the deep copy of the array or the object until and unless you don't have nested data. If you have nested data in Array or Object, then you will be having a shallow copy of them.
Be careful while using them, as you might run into bugs.
Another scenario for using Spread Operator could be finding Min or Max from a set of numbers while dealing with Math object in javascript.
let arr1=[1,2,3];
let max=Math.max(arr1);
In the above code, Math.max() method doesn't take an array as an input. So this might throw an error here or it may not provide the desired output.
let arr1=[1,2,3];
let max=Math.max(...arr1);
Math.max or Math.min wants numbers as input. So as explained above, spread operator will pull out the values from arr1 and simplify the array to numbers.
There might be more cases where we could use spread operator, but I personally like to use them in these scenarios.
If you find this useful, please give it a thumbs up๐.
Thank you.