I'ts important to note that Object.assign is a function which modifies and returns the target object. In Samantha's example using the following,
constcloneFood=Object.assign({},food)
{} is the object that is modified. The target object is not referenced by any variable at that point, but because Object.assign returns the target object, we are able to store the resulting assigned object into the cloneFood variable. We could switch our example up and use the following:
Obviously the value of beef in our food object is wrong, so we can assign the correct value of beef using Object.assign. We aren't actually using the returned value of the function at all, but we are modifying our target object which we have referenced with the const food.
Spread on the other hand is an operator which copies properties of one object into a new object. If we wanted to replicate the above example using spread to modify our variable food...
...we get an error, because we use spread when creating new objects, and therefore are assigning a whole new object to food which was declared with const, which is illegal. So we can either choose to declare a new variable to hold our new object in, like the following:
What is difference between spread and object.assign?
I don't think there is a difference aside from syntax in this case. The triple dot expression
...
also means rest which does not meanObject.assign
.For more information see 2ality.com/2016/10/rest-spread-pro...
I'ts important to note that
Object.assign
is a function which modifies and returns the target object. In Samantha's example using the following,{}
is the object that is modified. The target object is not referenced by any variable at that point, but becauseObject.assign
returns the target object, we are able to store the resulting assigned object into thecloneFood
variable. We could switch our example up and use the following:Obviously the value of
beef
in ourfood
object is wrong, so we can assign the correct value ofbeef
usingObject.assign
. We aren't actually using the returned value of the function at all, but we are modifying our target object which we have referenced with the constfood
.Spread on the other hand is an operator which copies properties of one object into a new object. If we wanted to replicate the above example using spread to modify our variable
food
......we get an error, because we use spread when creating new objects, and therefore are assigning a whole new object to
food
which was declared withconst
, which is illegal. So we can either choose to declare a new variable to hold our new object in, like the following:or we could declare
food
withlet
orvar
which would allow us to assign a whole new object:Got it. Thank you!
Thanks for chiming in and helping answer this question. This is great, let me add it to the code notes π
Thu explanation is swift. Thanks