Home > Blockchain >  Affects of object assignment within a function on global object values
Affects of object assignment within a function on global object values

Time:07-04

Can someone please help explain why the value property of obj1 remains the same while in obj2 it changes? I know it has to do with obj1 being assigned to obj2 within the change function but I'm not exactly sure why. Thanks!

let obj1 = {
  value: "a"
}

let obj2 = {
  value: "b"
}


function change(obj1, obj2) {
  obj1 = obj2
  obj1.value = "c"
}

change(obj1, obj2);


console.log("obj1: ", obj1, "obj2: ",obj2);

CodePudding user response:

Let's rename some variables so you can see what's going on

let obj1 = {
  value: "a"
}

let obj2 = {
  value: "b"
}


function change(param1, param2) {
  param1 = param2
  param1.value = "c"
}

change(obj1, obj2);


console.log("obj1: ", obj1, "obj2: ",obj2);

Now as you can see, obj1 is never changed. What you are changing is parameter of change function that is named the same as variable from outer scope.

CodePudding user response:

This is because variables of objects are actually pointers to the object. That's why when they are passed to a function, any changes of the pointer properties would change the actual object. Whereas, if you simply assign a value to a variable of type object, then the pointer itself is changed, not the object.

So obj1 = obj2 sets the obj1 pointer to be obj2 pointer. Now, if obj1.value = "c" then a property of the object obj1 (which is now obj2) will change, affecting the original object.

  • Related