12

Having

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

What are the differences between

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

And

obj = {...obj,  c: 3 };
2
  • Check compiled version and proposal Commented Jul 19, 2016 at 15:09
  • OK, so the spread operator for object literals isn't ES6, while Object.assign is. Commented Jul 19, 2016 at 15:14

1 Answer 1

39

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
So object spreading is more preferable and safer than the Object.assign @user6445533

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.