The difference between the distribution of Object.assign and the object

Having

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

What's the difference between

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

and

 obj = {...obj, c: 3 }; 
+5
source share
1 answer

The difference is that when using the spread you always create a new object:

 const a = { name: 'Joe Bloggs' } const b = { ...a, age: 27 }; console.log(a === b) //=> false 

However, using Object.assign , you can mutate an existing object:

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

You can still achieve object propagation behavior with Object.assign by passing the object literal as the first argument:

 const a = { name: 'Joe Bloggs' } const b = Object.assign({}, a, { age: 27 }); console.log(a === b) //=> false 
+16
source

All Articles