clean-code-javascript icon indicating copy to clipboard operation
clean-code-javascript copied to clipboard

Set default objects with Object.assign

Open rtm opened this issue 5 years ago • 5 comments

No, you should use object spread syntax here.

config = {
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true
      ...config};

rtm avatar Jan 19 '20 19:01 rtm

There is a pull request for it already: #204

rudotriton avatar Jan 22 '20 00:01 rudotriton

The pull request (#204) has been closed, it should probably be reopened.

spartanatreyu avatar Aug 30 '21 00:08 spartanatreyu

Please clarify a bit on what makes spread syntax better than Object.assign() ?

aanhlle avatar Mar 18 '22 04:03 aanhlle

It's simpler.

Spread syntax didn't exist when Object.assign was created, but now we have spread syntax to make things clearer and more concise.

Also, Object.assign has a footgun where calling it would call the passed object's setters, potentially triggering side effects if the setters were sloppily made.

spartanatreyu avatar Mar 18 '22 05:03 spartanatreyu

To clarify what @spartanatreyu wrote, MDN Web Docs says:

Note that Object.assign() can be used to mutate an object, whereas spread syntax can't.

const obj1 = { foo: "bar", x: 42 };
Object.assign(obj1, { x: 1337 });
console.log(obj1); // { foo: "bar", x: 1337 }

Mutations in code are generally considered detrimental because they make it more difficult to reason about the code; you have to keep track of various states mentally. For this reason, the React framework leans towards a functional programming style, where side effects are isolated and mutations are minimized or avoided altogether.

Ever since I learned about the spread operator, I found no reason to use Object.assign anymore, I could express everything with the spread operator so far.

rkrisztian avatar Sep 01 '23 13:09 rkrisztian