Search code examples
javascriptecmascript-6ecmascript-next

Difference between Object.assign and object spread


Having

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

What are the differences between

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

And

obj = {...obj,  c: 3 };

Solution

  • 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