DEV Community

Discussion on: Modern JavaScript, 10 things you should be using, starting today

Collapse
 
digioi profile image
Mike DiGioia • Edited

I don't think your NO spread for objects is right, I would likely do it like

const heroWIthWeapon = Object.assign({}, hero, {weapon: "sword"})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andrewbridge profile image
Andrew Bridge

I was thinking exactly this.

Even better: with this approach, you can choose to merge elements into an pre-existing object which can help with keeping object references and reduces the need for the engine to garbage collect short-lived objects.

Feels like a better approach!

Collapse
 
softchris profile image
Chris Noring

hi Mike, are you saying this code should use Object.assign()?

let keys = Object.keys(hero);
let obj = {};

for(var i=0; i< keys.length; i++) {
   obj[keys[i]] = keys[props[i]];
}
Enter fullscreen mode Exit fullscreen mode

Because my point was to showcase how painful it can be without spread? Help me understand, thanks :)

Collapse
 
digioi profile image
Mike DiGioia

I get that, but just because you can do something more painfully doesn't mean that it can't be done simpler. On top of that, there is no assignment of the weapon key.

I think it can be argued that
{ ...hero, weapon: "sword"} is easier to read than Object.assign({}, hero, {weapon:"sword")

Thread Thread
 
softchris profile image
Chris Noring

yes I agree that spread is easier to read than Object.assign().. so are you saying that it doesn't have to be as painful as looping through the keys but rather Object.assign is there and if you want to improve on that use spread syntax?

Thread Thread
 
digioi profile image
Mike DiGioia

I think that is fair to say. Since prior to browser support that was what the transpilers often did for you.