I was reading an interesting topic on StackOverflow about the difference between _.assign and _.extend.

First of all, the result using Object.assign, _.assign and _.extend are actually the same.

They have the same result

You might wonder why did the copies b.a var change ? Javascript is a pass-by-sharing language. Whenever you declare a variable and assign an object to it, as i said, you assign the object to the variable : it doesn’t copy it in any way, it just holds a reference to it.

x holds references but changes are made to original objects

So when creating a copy of foo using the differents functions above, I actually make a shallow copy of these (read : reassign the parameters of “foo” to the new object). So, every object holds a parameter called “a” pointing to an Integer. This one doesn’t change when i update foo because integers are immutable. As the Object.assign() documentation says :

Therefore it assigns properties versus just copying or defining new properties

But what’s happening when foo.b.a change ? I know my variables assign, _assign and _extend hold a shallow copy of foo and then a shallow copy of b, which is a reference. It means that every shallow copy of foo will have an object “b” being a reference to the same object.

Whenever one object updates the “b” reference, every other object change as well. That’s why my logs print the new value of “b”.

This is also the reason there are so much talk about immutability : if “b” is an important object and you want to keep track of his changes, how can you tell who updated “b” and why ?