Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Object.assign and object spread [duplicate]

Having

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

What are the differences between

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

And

obj = {...obj,  c: 3 };
like image 952
Marco Scabbiolo Avatar asked Jul 19 '16 14:07

Marco Scabbiolo


People also ask

What is the difference between object assign and object create?

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.

What does object assign mean?

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.

Does object assign create a copy?

Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

Does spread copy 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.


1 Answers

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
like image 181
sdgluck Avatar answered Oct 15 '22 02:10

sdgluck