As per pass-by-reference mechanism in JavaScript
Let's get this out of the way: there is no pass-by-reference mechanism in JavaScript. Pass-by-reference is a very specific feature. To know whether a language supports it, you should check whether it is possible to pass a variable with an immutable value to a function (for instance an integer), and after that call see that this variable has a different immutable value. If this is not possible, then the language does not support pass-by-reference. JavaScript does not support it. C does not support it. C++ does support it (by declaring a function parameter with &
).
As to your code example; let's visualise it.
First phase
After the first two var
statements we get this:
objOne
↓
┌───────────┐
│ x: 1 │
│ y: 2 │
└───────────┘
↑
objTwo
Only one object was created (using object literal syntax).
After objTwo.x = 2
, we get:
objOne
↓
┌───────────┐
│ x: 2 │
│ y: 2 │
└───────────┘
↑
objTwo
Only one property value was changed, in the only object that was created. Whether you look at the object via variable objOne
or objTwo
does not make a difference.
Second phase
objTwo = {}
creates a second object and assigns its reference to objTwo
. Now we have two, distinct objects:
objOne
↓
┌───────────┐
│ x: 2 │
│ y: 2 │
└───────────┘
objTwo
↓
┌───────────┐
└───────────┘
You cannot change which object objOne
is referencing without making an assignment to objOne
. Even though objOne
and objTwo
first referenced the same object, these variables are still distinct references. In the first phase we saw we can mutate the object that objOne
references, but it is still the same object -- just one that was subject to some mutation. It is not possible to make objOne
reference another object by making an assignment to objTwo
. You really need to assign to objOne
to make that happen.
Conclusion
There is no pass-by-reference mechanism in JavaScript. In JavaScript objects are accessed and manipulated through references. objTwo
is not an alias for objOne
, it only is a duplicate reference for the same object. As soon as another reference is assigned to objTwo
, we have two distinct references.