Cover image for Object Assign and Spread

Object Assign and Spread

codefinity profile image Manav Misra ・Updated on ・2 min read

'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 priority.me 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 repl.it 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...


Editor guide