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
  • 21,342
  • 4
  • 27
  • 50
Varun Sharma
  • 1,347
  • 1
  • 12
  • 35

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
  • 32,829
  • 2
  • 44
  • 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

iblamefish
  • 4,631
  • 3
  • 32
  • 44
Ferus7
  • 677
  • 1
  • 11
  • 21
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,147
  • 1
  • 16
  • 33