Question:
Why does the first modification work (when I reassign properties of the object) but not the second (when I reassign the whole object)?Answer:
Consider the example below:We create an object and assign it to variable
foo
and then we assign foo
to bar
. So, now both foo
and bar
refer to the same object, as illustrated in the diagram below.
Next let’s change the
val
field of the object i.e. assigned to bar
. We notice that the change is reflected by both the variables foo
and bar
and this is because both the variables refer to the same object.
Next we assign a new object to
bar
. Notice this doesn’t effect the object that foo
refers to, bar
is simply now referring to a different object.
Let’s relate this to the
forEach
example in your question. So, in every iteration of the forEach
loop, the item
argument in the callback function points to an object from the array and when you change a field from this item
argument it changes the object in the array but when you assign item
to a new object it does nothing to the object stored in the array.If you want to replace the entire object with a new one, there are several approaches you could take, two of which are mentioned below:
- Finding the index where the object is stored and replacing it with a new object.
- Another really common approach is to
map
over the array and create a new array with that one object replaced.
If you have better answer, please add a comment about this, thank you!