loading...

JavaScript object spread explained

mcrowder65 profile image Matt Crowder ・1 min read

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"
};

You should just see updatedMetadata as such:

const updatedMetadata = {
  first: "Matt",
  last: "Crowder",
  last: "Jenkins"
};

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"
}

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

So be careful where you place your spread syntax!

Posted on by:

mcrowder65 profile

Matt Crowder

@mcrowder65

Software Engineer at Appian, previously at Walmart Labs. Co-organizer of novajavascript.com, public speaker, teacher, codementor.io/mcrowder65

Discussion

markdown guide