The assignment =
operator only generates a reference to an object but does not copy it. In this case obj1 already exists and the reference is not made. JavaScript is a bit confusing with objects and assignment operators (versus other variables).
Object assigment
By using the assigment =
operator you are telling the compiler to make a reference to an object not a copy / shallow copy. If this was a new variable it would allow 2 different ways to get to the same data (like a pointer in C). However obj1 already exists (it's a parameter on the function) hence it won't make that reference.
Now you change obj2 to c, obj1 stays at a (because the reference isn't made). Hence the result is a b c c a c
and not a b c c c c
.
If you want to change obj1, you'll have to modify it in the change() function directly, you cannot make a reference to it using =
. Or create a clone/copy of obj1 using .assign().
For a good article (or well I like it) on objects:
https://scotch.io/bar-talk/copying-objects-in-javascript
However be careful when hoisting variables like that, you are technically changing variables outside of the change function. You may want to pass them back and assign them at the same level instead of inside the change function.