Ad

What Is Right To Use Spread Operator Or Object.assign In Redux?

I had a little bit of confusion whether to use Spread operator or Object.assign in reducer function to apply changes to the target object.

const toggleTodo = (todo) => {
  return Object.assign({}, todo, {
    completed: !todo.completed
   });
 };

Then above mention code is using Object.assign method, and the below one is using spread operator

const toggleTodo = (todo) => {
return {
  ...todo,
  completed: !todo.completed
  };
};

Which is the appropriate method in both of these

Ad

Answer

The object spread operator (...) doesn't work in browsers, because it isn't part of any ES specification yet, just a proposal. The only option is to compile it with Babel (or something similar).

Here's the compiled code from Babel's REPL.

var _extends = Object.assign || /* a polyfill */;

return _extends({}, todo, {
  completed: !todo.completed
});

As you can see, it's just syntactic sugar over Object.assign({}).

There's no right option.

As far as I can see, these are the important differences.

  • Object.assign works in most browsers (without compiling)
  • ... for objects isn't standardized
  • ... protects you from accidentally mutating the object
  • ... will polyfill Object.assign in browsers without it
  • ... needs less code to express the same idea
Ad
source: stackoverflow.com
Ad