Search code examples
javascriptecmascript-6

Object spread vs. Object.assign


Let’s say I have an options variable and I want to set some default value.

What’s is the benefit / drawback of these two alternatives?

Using object spread

options = {...optionsDefault, ...options};

Or using Object.assign

options = Object.assign({}, optionsDefault, options);

This is the commit that made me wonder.


Solution

  • For reference object rest/spread is finalised in ECMAScript 2018 as a stage 4. The proposal can be found here.

    For the most part object assign and spread work the same way, the key difference is that spread defines properties, whilst Object.assign() sets them. This means Object.assign() triggers setters.

    It's worth remembering that other than this, object rest/spread 1:1 maps to Object.assign() and acts differently to array (iterable) spread. For example, when spreading an array null values are spread. However using object spread null values are silently spread to nothing.

    Array (Iterable) Spread Example

    const x = [1, 2, null , 3];
    const y = [...x, 4, 5];
    const z = null;
    
    console.log(y); // [1, 2, null, 3, 4, 5];
    console.log([...z]); // TypeError
    

    Object Spread Example

    const x = null;
    const y = {a: 1, b: 2};
    const z = {...x, ...y};
    
    console.log(z); //{a: 1, b: 2}
    

    This is consistent with how Object.assign() would work, both silently exclude the null value with no error.

    const x = null;
    const y = {a: 1, b: 2};
    const z = Object.assign({}, x, y);
    
    console.log(z); //{a: 1, b: 2}