iterating and storing object equal to itself

ann*_*123 10 javascript

Can someone help me in understanding the reason why someone would iterate when it's value is equal to it?

for example

let subStyle = {
      width: 300,
      height: 50,
      borderRadius: 20,
      backgroundColor:  theme.primaryBlue
    };

subStyle = {
        ...subStyle,
        backgroundColor: theme.primaryWhite,
        borderWidth: 2,
        borderColor: '#707070'
      }
Run Code Online (Sandbox Code Playgroud)

i.e in the above code, what could be the reason for doing the same?

subStyle = {
        ...subStyle,
        backgroundColor: theme.primaryWhite,
        borderWidth: 2,
        borderColor: '#707070'
      }
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 7

They're copying the properties from the object subStyle refers to into a new object (then overwriting one of them and adding two more), then assigning that new object to the subStyle variable. This is quite standard when you aren't allowed to modify the original object because something else may be using it (React state, for instance).

Simpler example:

let o1 = {a: "ay", b: "bee"};
let o2 = o1; // Something else is using the same object

// We need to create a new, updated object without
// affecting others who have access to the current one
o1 = {...o1, b: "BEE", c: "see"};

// The original is unchanged
console.log(o2);

// The new one has the updates
console.log(o1);
Run Code Online (Sandbox Code Playgroud)

That ...someObject within an object initializer is called property spread. It was added to JavaScript in ES2018.

I should note that it's not iteration in JavaScript terms (though of course it's similar) and it doesn't require that the object be iterable. (In constrast, ... in an array initializer is iteration and does require that what you use it on be iterable.)