iterating and storing object equal to itself

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);

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.)


Because let's say you want to update that object in an immutable way. The mutable way would be:

let x = {a:1, b:2};
x.a=123;

Immutable way, you create a new object, copy properties of old one using ... operator (in a shallow way), and also assign a new property (or overwrite existing one):

let x = {a:1, b:2};
let y = {...x, a:123} // We created a new object and copied properties from x to it, also update value of a

This way you get object with same contents as in the first example, but you didn't modify x.

Tags:

Javascript