What is the difference between:
cartItem = {...cartItem, amount: newAmount}
and
cartItem.amount = newAmount
Advertisement
Answer
The first is an assignment to cartItem
, while the second is a mutation of the object held by cartItem
.
The first creates a new object. The previous value of cartItem
referenced an object that could still be referenced by another reference. Demo:
let newAmount = 13; let cartItem = { name: "cart", amount: 42 }; let myRef = cartItem; cartItem = {...cartItem, amount: newAmount}; console.log(myRef); // still the old object // Let's do this again, with the other technique cartItem = { name: "cart" }; myRef = cartItem; cartItem.amount = newAmount; console.log(myRef); // the mutated object
So there is a difference which can be noticeable when you have another reference to the original object.
This other reference, could be a variable of the caller of a function:
function assignment(cartItem, newAmount) { cartItem = {...cartItem, amount: newAmount}; } function mutation(cartItem, newAmount) { cartItem.amount = newAmount; } // scenario 1 let cartItem = { name: "cart", amount: 42 }; assignment(cartItem, 13); console.log(cartItem); // Has not changed -- "old" object // scenario 2 mutation(cartItem, 13); console.log(cartItem); // Has changed -- "old" object has mutated!