You need to break this down and understand the variables in different lexical scopes.
a
in the global lexical scope:
var a = {x:1};
a = {y:2};
The above initialization would resolve to:
a = {y:2};
//hence at this global lexical scope
//`lexicalscope = {"a":{y:2}};`
Now, let us see the variables inside the lexical scope of the function:
function _change(b){
// at the function's `lexicalEnvironment = {"b":{y:2}}`
b= { y:3};
// at this point `lexicalEnvironment = {"b":{y:3}}`
return b; //returned {y:3}.
}
When the function is invoked with a
as its parameter.
_change(a); // obtained {y:3} but not captured.
I would love to include the beautiful explanation for why the value of a
does not change outside the scope of the function in this answer here, but, do not want to duplicate the original answer. Would like to share the relevant part though,
In practical terms, this means that if you change the parameter itself (as with a),
that won't affect the item that was fed
into the parameter. But if you change the INTERNALS of the parameter, such as b.y = 3,
that will propagate back up.
Again, printing their values in the global lexical scope.
console.log(a.y); // still in the global lexical environment a.y = 2;
console.log(a.x); // `a.x` is undefined in the global Lexical Environment.