DEV Community

Matt Crowder
Matt Crowder

Posted on

JavaScript object spread explained

If you want to update a piece of an object while creating a new object, then the spread syntax is the way to go.

When you see ..., you should just think of flattening the object.

When you see this:

const metadata = { first: "Matt", last: "Crowder" }; const updatedMetadata = { ...metadata, last: "Jenkins" }; 
Enter fullscreen mode Exit fullscreen mode

You should just see updatedMetadata as such:

const updatedMetadata = { first: "Matt", last: "Crowder", last: "Jenkins" }; 
Enter fullscreen mode Exit fullscreen mode

Key/value assignments are read from top to bottom, so the last key's value will take priority in setting the value.

And now updatedMetadata will have the value of:

{ first: "Matt", last: "Jenkins" } 
Enter fullscreen mode Exit fullscreen mode

So the spread flattens out the object wherever you place it, so if we had placed the spread metadata after last: "Jenkins", then we would get no updates!

const metadata = { first: "Matt", last: "Crowder" }; const updatedMetadata = { last: "Jenkins", ...metadata }; // results in  const updatedMetadata = { last: "Jenkins", first: "Matt", last: "Crowder" }; // which gives us nothing 
Enter fullscreen mode Exit fullscreen mode

So be careful where you place your spread syntax!

Top comments (1)

Collapse
 
rogasper profile image
rogasper

Nice, i know understand