DEV Community

Cover image for Object Assign and Spread
Manav Misra
Manav Misra

Posted on • Updated on

Object Assign and Spread

'Merge & Mutate'

We can use Object.assign() to 'merge' object literals. assign is a variadic parameter method. This just means that we can pass as many arguments, i.e. object literals into it as we want.

The general behavior is that the first argument will receive any/all πŸ”‘s from any/all of the remaining arguments, with priority given to the righthand most argument. It's an RTL operation.

If that first argument already has a given πŸ”‘, it's value will be overridden by the first 'argument object' with the same value starting from the right. Only the first 'argument object' will be overwritten.

That's confusing πŸ˜•! An example should help:

Here, we see that you - the first argument was the only one with its values overridden. And, who did the overriding? Well, the rightmost argument, someoneElse took contributed whatever someoneElse didn't have, and you held onto myOwnKey.

None of the other 'object arguments' were affected - only the first one, you.

Assembling a New Object

This time, we avoid mutating any of the object literals; Instead, we 'assemble' all of the πŸ”‘s from each of the 'existing objects' into a 'new' object literal.

Refactoring ♻️ Object.assign ➑️ ...

This time we achieve the same results, but with the cleaner spread syntax: ....

We are 'spreading' all of the things in each of the other object literals and 'wrapping them up' into a 'new' object literal; That's where the surrounding { } come in to play.

Hopefully, the examples helped you understand how to re-use objects.

React relies on avoiding mutations, so it's critical that you understand how to do this, and the simplest way is to use: ....

Update: Here's how we can use this technique to 'compose' new objects...

Top comments (0)