Damm Object Spread Operator.

Rabin Gaire
2 min readFeb 4, 2019

What is Object Spread Operator in Javascript?

I thought I was very much familiar with this concept, I have written a lot of code with the help of this syntax, Object Spread Operator in Javascript makes it really easy to update the value of the keys. I love the concise syntax and Its much cleaner and easier to write and understand.

Here it is how we use Object Spread Operator in Javascript:

It looks clean, readable and concise, right?

And it is also an immutable approach, meaning the changes on the new object updatedInfo does not mutate the values of the keys on myInfo. Cool Right?

Previously we used to write the above code similar to this:

Did you Spot the problem?

Changing the value of age and address on updatedInfo also changes the value of myInfo. Because while copying the myInfo object into updatedInfo we are not copying the actual value but we are copying the reference type, meaning both updatedInfo and myInfo points to the same memory location, this was a big problem and lead to a lot of bugs if the programmer was not careful enough.

To solve this problem developer used to write code similar to this:

Object.assign solved the problem of mutation, as it used to create a new object at different memory location by copying the value of the parent/root object as in our case myInfo.

Above syntax is great but it looks weird, people coming from a different programming background can find it a bit confusing.

Why the hell are you assigning this object with the empty object are the most common questions.

So here comes the Object Spread Operator to rescue but it is also a double-edged sword. Why? Let me explain !!!

A couple of days ago I was working on this project where I wrote a code similar to this:

Looks good right?

But this code has a big problem, It does not actually update the value of age and address, hell it does not do a thing. Why? Because what we are actually doing is we have an object with keys age and address and we are updating those values with the respective values from myInfo. Making the code useless.

I thought I was doing everything right, but after an hour of debugging I finally figured it out and felt stupid for the kind of mistake I have made.

To be fair a lot of developers trip with this, while maintaining a huge code base we sometimes write code similar to this, I suggest everyone reading this blog to be extra careful while writing Object Spread Operator else you might have to say Damm Object Spread Operator.

--

--