olivier olivier - 3 months ago 25
Javascript Question

Spread operator 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?

Use the spread operator

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


Or use Object.assign

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


This is the commit that made me wonder.

JMM JMM
Answer

This isn't necessarily exhaustive.

Spread syntax

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

Advantages:

  • If authoring code for execution in environments without native support, you may be able to just compile this syntax (as opposed to using a polyfill). (With Babel, for example.)

  • Less verbose.

Disadvantages:

  • A proposal, not standardized. (Consider what you'd do if you write it now and it doesn't get standardized.)

  • Literal, not dynamic.


Object.assign()

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

Advantages:

  • Standardized.

  • Dynamic. Example:

    var sources = [{a: "A"}, {b: "B"}, {c: "C"}];
    options = Object.assign.apply(Object, [{}].concat(sources));
    

Disadvantages:

  • If authoring code for execution in environments without native support you need to polyfill.

  • More verbose.


This is the commit that made me wonder.

That's not directly related to what you're asking. That code wasn't using Object.assign(), it was using user code (object-assign) that does the same thing. They appear to be compiling that code with Babel (and bundling it with Webpack), which is what I was talking about: the syntax you can just compile. They apparently preferred that to having to include object-assign as a dependency that would go into their build.