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'
}
i.e in the above code, what could be the reason for doing the same?
subStyle = {
...subStyle,
backgroundColor: theme.primaryWhite,
borderWidth: 2,
borderColor: '#707070'
}
Essentially for keeping the same values in the object.
When you do subStyle = { ... }
you are overwriting the object.
If you do subStyle = { ...subStyle }
you will copy all you had before inside subStyle
and the rest that you add will be added along
An illustrative example:
let myObject = {
a: 'a',
b: 'b'
}
console.log('My object: ', myObject)
myObject = { ...myObject }
console.log('Copying my object with spread operator: ', myObject)
myObject = {
...myObject,
c: 'c',
d: 'd'
}
console.log('Adding new elements to my copied object with spread operator: ', myObject)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With