JavaScript: Spread Operator In a glance

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.

After release of ES6 and the Babel, writing JavaScript has become incredibly dynamic, from new language syntax to custom parsing like JSX. I’ve become a big fan of the spread operator, three dots that may change the way you complete tasks within JavaScript.

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.

There’s three such places: functions calls, elements in arrays, and key-value pairs in objects. Let’s breathe a bit of life into those words and have a look at what this thing can do. Here are the some lesser known tricks when using spread with JavaScript.

The Spread Operator in Arrays

Let’s say we’ve got an array card which we want to insert into a new array:

spread operator

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).

Copying arrays

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…

Copying objects

Just as with shallowly cloning arrays, I also shallowly clone objects regularly. Until recently, I used to go with this method Object.Assign()

I’ve always liked Object.assign() well enough, but now I use spread operator that does the job with far more grace

Combining objects

Merging objects also becomes easier with the spread operator, an operation traditionally performed with Object.assign().

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

  • GeeksforGeeks

UI Developer @HCL Technologies