DEV Community

Discussion on: 5 Uses for the Spread Operator

Collapse
tbutterwith profile image
Tom Butterwith • Edited on

Great examples!
Note that for merging objects, the keys in the later objects take precedence. e.g.

let obj1 = { a:1, b:2, c:3 };
let obj2 = { a:2 };

let obj3 = {...obj1, ...obj2};
// obj3 is { a:2, b:2, c:3 }
Enter fullscreen mode Exit fullscreen mode
Collapse
laurieontech profile image
Laurie Author

Absolutely important to point out! Thanks for mentioning it.

Collapse
drewtownchi profile image
Drew Town

This is usually how I do optional options in an object.

If I have a function that accepts an object of options I'll spread them into the default options. It works great because all of the latter keys take precedence like you stated.

Collapse
felipperegazio profile image
Felippe Regazio

i do the same ;P

Collapse
jwkicklighter profile image
Jordan Kicklighter

This totally works, but have you tried using default values in the function signature? I believe that was added in ES6, but I can't remember for sure.

function (name: 'John', id: 5) {
  ...
}
Thread Thread
drewtownchi profile image
Drew Town

I have and it works well for simple function signatures. But, when you reach a point where you have 5, 6, 7 optional parameters and you need to change the last one this pattern becomes a real pain. The problem is there is no way to invoke named function parameters, you have to do it by order.

Thread Thread
jwkicklighter profile image
Jordan Kicklighter

If you add curlies, you can still specify the arguments in the signature but treat it as an object. Best of both worlds.