2

These two simple examples were given to me to explain objects in javascript. I understand the first example, but what eludes me is why in the second (highly similar) example o isn't overwritten with an empty object?

function foo(obj) {
    obj.x = 7;
}
var o = {x: 5};
foo(o);
console.log(o.x); // 7

It seems to me that in the following example, undefined should be logged:

function foo(obj){
   obj = {};
}
var o = {x: 5};
foo(o);
console.log(o.x); // 5

But it isn't, how come? What is the difference between these two examples, that causes o not to be overwritten in the second example?

3 Answers3

1

The parameter obj is a separate variable from o. It receives a copy of the value of p when the function is called. Changing the value of obj has no effect on o.

JavaScript is purely a pass-by-value language. It's not possible to create an alias for a JavaScript variable, so there's nothing that a called function can do to modify the value of a variable in the calling environment.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • But from what I understand, javascript assigns objects to variables by reference (or more specifically, a value that is a reference to the object). Which is why the first example works. But shouldn't that also mean that in the second example the object would be overwritten? – vkjb38sjhbv98h4jgvx98hah3fef Apr 13 '15 at 14:06
  • 1
    @DrMister no. The *value* of `o` is indeed a *reference* to an object. When the function is called, a *copy* of that reference is made and handed over to the function. Modifying `obj` modifies that distinct variable, and does not affect the value of `o`. – Pointy Apr 13 '15 at 14:07
1

In both examples you pass a copy of a reference to the object, not the object itself

In example 1 you change something within the object, fine In example 2 within the function you change the reference itself, it's now pointing to something other than the original object, outside of the function the reference is still the same

This is pass by value v pass by reference

tony
  • 2,178
  • 2
  • 23
  • 40
0

In your function foo , when you set obj = {} you are changing the reference that obj refers to. but you are not changing what o references.

Charbz
  • 536
  • 3
  • 13