The spread operator is awesome. It can do so much — it’s efficient, readable, and can save a whole load of mess. I have used this many times.
So, What Actually is the Spread Operator?
Spread Operator represented by Three dots:
Three very powerful dots, that allow you to expand arrays or iterable objects in places where array elements or key-value pairs would be expected.
The Spread Operator in Arrays
Let’s say we’ve got an array card which we want to insert into a new array:
When you see the spread operator in an array, it’s just expanding one array into another.
Manipulating Arrays with the Spread Operator
There’s a few things you can do with spread syntax to manipulate arrays. I’ll include a couple of examples to show you what it can do!
Adding values to arrays
Self explanatory and beautiful. Using the spread operator allows you to turn numbers into a flat array (rather than a nested array, which would be the result without spread syntax).
If you want to make a copy of an array, you shallowly clone arrays all the time. Do you do it like this? We all used this sometime earlier.
Yeah, so did I for a while! But then I discovered that you can actually just use the spread operator to make coding easier…
Just as with shallowly cloning arrays, I also shallowly clone objects regularly. Until recently, I used to go with this method
I’ve always liked
Object.assign() well enough, but now I use spread operator that does the job with far more grace
Merging objects also becomes easier with the spread operator, an operation traditionally performed with
Lets compare with the spread syntax way of doing things:
This is all pretty similar to cloning and merging with arrays, but it’s fabulous that we’ll be able to do this with objects too.
Resources to learn from