When working with JavaScript, one common point of confusion is the way variables are treated based on their data type. Variables of primitives are passed by value, while variables of objects are passed by reference. However, in function arguments, both primitives and references are passed by value.
In my experimentation, I came up with the following code, but I'm struggling to fully understand it:
> function setName2(obj) {
... obj.name="matt";
... obj = new Object();
... obj.name="obama";
... }
If I do this:
var person = new Object();
person.name = "michelle";
And then call:
> setName2(person);
I get:
> person.name;
'matt'
This result makes sense because the new object created within the function is only local and does not affect the global 'person' object.
But what happens if I first create an object like this:
var obj = new Object();
obj.name = "michelle";
And then run:
> setName2(obj);
The outcome is still the same. Does this mean that the compiler distinguishes between the global and local variables named 'obj,' recognizing each as a reference to a different memory location in the heap, or is there another explanation for this behavior?