1

I'm trying to understand a complexity someone showed me in JavaScript. Consider the following simple function:

function myFunction(p) {
    p.property = 1;
}

var obj = {property: 0};
console.log(obj); // {property: 0}
myFuncton(obj);
console.log(obj); // {property: 1}

Let's repeat this, but instead of overwriting one part of the object, let's overwrite the whole object:

function myFunction(p) {
    p = {property: 1};
}

var obj = {property: 0};
console.log(obj); // {property: 0}
myFuncton(obj);
console.log(obj); // {property: 0}

Why does obj not get replaced here as expected?

Sam Bartlett
  • 78
  • 1
  • 9
  • Javascript does not use pass by reference. The Java guys would call it pass-by-value-but-you-have-to-keep-in-mind-that-the-value-you're-passing-is-really-a-reference. I wish there was something less cumbersome; "pass by value" gives the wrong impression and "call by object" or "call by sharing" are too obscure. – user2357112 Feb 20 '17 at 20:29

2 Answers2

2

Why does obj not get replaced here as expected?

Because when you call your function you pass a copy of the reference to the object obj. That means you can change/modify the properties of the object you pass to the function but you can't change the actual reference.

In terms of code:

// creates an object and a reference to this object is assigned to the obj
var obj = {property: 0};

function myFunction(p) {
    p = {property: 1};
}

// Here you pass a copy of the reference.
myFunction(obj);

Now whatever you do is on this copy, like modifying it's property called property is reflected to the actual object, since obj and the copy of it's reference you pass point to the same object. This is what happening to the first case. In the second case you just try to assign a new value to the copy of the reference you passed. So nothing happens to the original reference.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

Because you're assigning a new value to a local variable within the function.

The first snippet works because you're modifying an object which you have a reference of. The second doesn't work because you're throwing the reference you have away and are assigning a different object to the variable instead.

deceze
  • 510,633
  • 85
  • 743
  • 889