Site is currently on development mode

Object.assign vs Object Spread in Node.js

Last updated 1 year ago by Valeri Karpov


The Object Rest/Spread Proposal reached stage 4 in 2018, which means it will be included in a future iteration of the ECMAScript spec. It's also been included in Node.js LTS since Node.js 8, so you can safely start using it today.

``` $ node -v v8.9.4 $ node

const obj = { foo: 1, bar: 1 }; undefined ({ ...obj, baz: 1 }); { foo: 1, bar: 1, baz: 1 } ```

The Object spread operator {...obj} is similar to Object.assign(), so which one should you use? Turns out the answer is a bit more nuanced than you might expect.

Quick Overview of Object Spread The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object. So {...obj} creates a new object with the same properties and values as obj. For plain old JavaScript objects, you're essentially creating a copy of obj.

const obj = { foo: 'bar' }; const clone = { ...obj }; // `{ foo: 'bar' }` = 'baz';; // 'bar'

Like Object.assign(), the object spread operator does not copy inherited properties or class information. It does copy ES6 symbols.

Read full Article