Having
var obj = { a: 1, b: 2};
What are the differences between
obj = Object.assign(obj, { c: 3});
And
obj = {...obj, c: 3 };
Create method is used to create object instance with an already declared object properties and it's prototype and assign it to a newly created prototype object and return's empty object. Assign method is used to assign object properties from source object to the target object and also return's the new object.
assign() The Object. assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
The spread operator makes deep copies of data if the data is not nested. When you have nested data in an array or object the spread operator will create a deep copy of the top most data and a shallow copy of the nested data.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With