Using the Spread Operator (…) in JavaScript

The spread operator is a useful tool to add items to arrays, and combining arrays or objects.

Simon Jacobs
3 min readMar 11, 2021

In JavaScript, the spread operator refers to the use of three dots () to expand an object into a list of arguments.

With the spread operator, you can:

  • Copy an array or an object
  • Concatenate or combine arrays or objects
  • Use an Array as arguments
  • Add to state in React

In my most recent project, which was essentially a reconstruction of the ever popular (and extremely useful) Evernote, I spent a lot of time debugging the below code:

Here, I couldn’t figure out why my state wasn’t updating with the new updatedNote. After meeting with my instructor and going over it again and again, it was simple, and it usually is but when you’re staring at code for hours on end, things tend to make less sense.

I’ll be writing a blog post on taking walks to clear your head and will link it here when I do. But for now let’s figure out why this wasn’t working:

The spread operator will take the existing object, in this case it is an instance of a Note object with a unique ID, a title and a body. I have updated these attributes via the form on my application and am sending the updated note to this function. Upon saving the edited note to the database, the note wasn’t actually updating. It was simply adding a new object of updatedNote, inside of the original note:

So that’s how you don’t use a spread operator, all I needed to do was simply return the updatedNote (thanks Ian!).

Here is the spread operator doing it’s magic:

In the above example I’ve created an object of a searchTerm, to allow my search function to have multiple attributes to search by, in this case a title, or a body.

In the event handler function, we define a key of an attribute with a default value of “title”, and value of the search term as an empty string. We then use the spread operator to take that existing object, and update it with the new values. This works because the keys are the same as the original from the existing object and voilà! We have our new search term and the attribute we’re searching by:

Finally, instead of using .push(), a spread operator is a cleaner (IMO) way of adding an item to an array:

In the above function, we take a newNote object and we want to add it to our existing array of notes. We could, of course, do this in a number of ways, but here we use the spread operator in our updatedNotes variable to take all of the existing notes, and we add our newNote object to that array.

That’s all folks! Thanks for reading. More to come on taking walks and balancing personal problems and coding bootcamps…and that will be a long one.

--

--

Simon Jacobs
Simon Jacobs

Written by Simon Jacobs

Just a dude trying to make cool stuff.

No responses yet