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

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

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.

More from Medium

Node.js server unit test with Jest, Sinon, Supertest

Reuse RabbitMQ connection

Handle Multiple Promises using Async/Await