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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
rogasper profile image
rogasper

Nice, i know understand

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series