First, about the question in the header (which is actually different from what you are demonstrating with the code examples):
"As I understand it, objects are passed by reference in JavaScript"
No, Javascript does not support passing a parameter by reference at all. All parameters are passed by value, but the value can be a reference.
Example:
var a = { answer: 42 }; function f(x) { alert(x.answer);
When a parameter is passed by value, the variable x is separated from the variable a , so assigning a new object x does not change the value of a .
Return to your code:
When you assign a link to an object from a variable to another, it copies the link, not the object. You get two variables that reference the same object.
Any of the variables can be used to access the elements in the object that your first code example demonstrates.
If you assign a new object to the first variable, you will replace the link in the variable; you will not overwrite the object it points to. The object remains intact, and the second variable still points to it. You get two variables that point to one object each, which demonstrates your second code example.
Guffa source share