1

I am a little confused about the way JavaScript treats objects passed as arguments to functions.

For example, in the following code:

var a = {
  val: "old"
};
var b = {
  val: "old"
};

function update(a, b) {
  a.val = "new";
  b = {
    val: "new"
  };
}

update(a, b);

console.log(a, b);

The output comes as:

enter image description here

The val property of a is changed but that of b is not. I read somewhere that Objects are passed by reference to functions. Can anyone please explain this behaviour.

Thanks in advance.

prasanth
  • 22,145
  • 4
  • 29
  • 53
Varun Sharma
  • 1,602
  • 1
  • 13
  • 37

3 Answers3

0

In the a case you are changing the object that variable a points to. In the b case you are creating a new object and making b points to this new object.

Ankur
  • 33,367
  • 2
  • 46
  • 72
0

When you make this

function update(a, b) {
  a.val = "new";
  b = {
    val: "new"
  };
}

you are pointing b to a new object, but only in the update function

clinton3141
  • 4,751
  • 3
  • 33
  • 46
Ferus7
  • 707
  • 1
  • 10
  • 23
0

Actually the object references are passed by value to the function, And that is why when you changed the property of a it reflected. But as you assigned a new object to b, b inside the function got referenced to the new object.

Jins Peter
  • 2,368
  • 1
  • 18
  • 37