Use JS object spread operator instead of Object.assign() pattern in Node 8

const foo = { a:1, b:2, c: 3}
const bar = { d:4, b:9 }
const foobar1 = Object.assign({}, foo, bar)
const foobar2 = { ...foo, ...bar }
console.log(foobar1, foobar2)
console.log(JSON.stringify(foobar1) === JSON.stringify(foobar2))

Object.assign() issues

The biggest problem with Object.assign() is that it modifies the first argument. If you omit the empty object literal {} it will modify the first parameter and return reference to it:

const foo = { a:1, b:2, c: 3}
const bar = { d:4, b:9 }
const foobar3 = Object.assign(foo, bar)console.log(foobar3, foo)
console.log(foobar3 === foo) // true

But the object spread syntax is …ugh

Yeah, I’ve got the same feeling at the beginning, but quickly got used to it. For array rest/spread syntax is already part of ES2015 standard and becomes wildly used. That’s no a surprise, because in JavaScript there was no clean way to do head+tail list transformations prominent in Functional Programming.

Object.assign() syntax from MSN docs.

Object spread syntax benefits

  • Less cluttered code thanks to sparse syntax
  • Prevents accidental object modification
  • Can be enforced using ESlint rule
  • Douglas Crockford says so:

--

--

Father. Husband. Solutions developer profesionally (software quite often). Arsenal supporter. Cyclist.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Brodziak

Adam Brodziak

Father. Husband. Solutions developer profesionally (software quite often). Arsenal supporter. Cyclist.