11

Having

var obj = { a: 1, b: 2};

What are the differences between

obj = Object.assign(obj, { c: 3});

And

obj = {...obj,  c: 3 };
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Marco Scabbiolo
  • 7,203
  • 3
  • 38
  • 46
  • Check [compiled version](https://babeljs.io/repl/#?evaluate=false&lineWrap=false&presets=es2015%2Cstage-2&code=obj%20%3D%20%7B...obj%2C%20%20c%3A%203%20%7D%3B) and [proposal](https://github.com/sebmarkbage/ecmascript-rest-spread) – Yury Tarabanko Jul 19 '16 at 15:09
  • OK, so the spread operator for object literals isn't ES6, while `Object.assign` is. –  Jul 19 '16 at 15:14

1 Answers1

38

The difference is that when using a spread you are always creating a new object:

const a = { name: 'Joe Bloggs' }
const b = { ...a, age: 27 };

console.log(a === b) //=> false

However using Object.assign it is possible to mutate an existing object:

const a = { name: 'Joe Bloggs' }
const b = Object.assign(a, { age: 27 });

console.log(a === b) //=> true

You still can achieve the behaviour of an object spread with Object.assign by passing an empty object literal as the first argument:

const a = { name: 'Joe Bloggs' }
const b = Object.assign({}, a, { age: 27 });

console.log(a === b) //=> false
sdgluck
  • 24,894
  • 8
  • 75
  • 90
  • 2
    Because you can't specify a target with object spread and thus can't mutate existing objects, it is actually safer than `Object.assign` and more consice. –  Jul 19 '16 at 15:27
  • **So object spreading is more preferable and safer than the `Object.assign`** @user6445533 – Siluveru Kiran Kumar Jul 10 '19 at 07:38