As noted in my comment to Ahmed Nuaman's answer, saying that the argument is passed by reference is incorrect. Proving that is trivial:
function change (x) {
//"replace" x with a different object?
x = {
a : 4
};
}
var o = { a : 6 };
change(o);
console.log(o.a); //6
If the argument would truly have been passed by reference, o.a
would have been 4
. However, the argument is passed by the reference value - in this case, the value is simply and object.
And that's why you observed the symptoms presented in the question: When you directly modified the argument, the object passed in was changed.
It's as if you got some ice-cream, then went back to the stand to ask for an extra scoop of vanilla. You still have the same cup, but with that extra something. Using that analogy in the example above, you ask for a new vanilla ice-cream: you still have the old one, and that hasn't changed (well, it may have melted a bit). In a pass-by-reference scenario, you would've dumped your existing ice-cream, and got a brand new one.
As a final note: This is not about scoping rules in js. If eg
wasn't passed to the second
function, it would've been unavailable to it.