1

I have two objects, a function, and some console.logs:

let obj1 = {
  value: "a"
}

let obj2 = {
  value: "b"
}

console.log(obj1.value)
console.log(obj2.value)


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

change(obj1, obj2);

console.log(obj1.value)
console.log(obj2.value)

RESULT:

a b c c a c

and I expected:

a b c c c c

Can someone explain why value is A and not C?

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48

3 Answers3

1
/* function scope obj1 and obj2, refer like function(f_obj1, f_obj2)
   f_obj1 is reference to global obj1
   f_obj2 is reference to global obj2 */
function change(obj1, obj2) {

  /* f_obj1 = reference of f_obj2 */
  obj1 = obj2;

  /* f_obj2 is referring global obj2 and value updated in global */
  obj2.value = "c";

  /* printing the f_obj1 and f_obj2 values */
  console.log(obj1.value)
  console.log(obj2.value)
}

// Now out of the function, So f_obj1 and f_obj2 are out of scope.
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

When you name the params to the function the same as global variables the function will create another space on memory to this variables. In this case the function only change the values inside itself...

Try:

let obj1 = {
  value: "a"
}

let obj2 = {
  value: "b"
}

console.log(obj1.value)
console.log(obj2.value)


function change() {
  obj1 = obj2;
  obj2.value = "c";
  console.log(obj1.value)
  console.log(obj2.value)
}

change();

console.log(obj1.value)
console.log(obj2.value)
Jackson D
  • 130
  • 6
0

The assignment = operator only generates a reference to an object but does not copy it. In this case obj1 already exists and the reference is not made. JavaScript is a bit confusing with objects and assignment operators (versus other variables).

Object assigment

By using the assigment = operator you are telling the compiler to make a reference to an object not a copy / shallow copy. If this was a new variable it would allow 2 different ways to get to the same data (like a pointer in C). However obj1 already exists (it's a parameter on the function) hence it won't make that reference.

Now you change obj2 to c, obj1 stays at a (because the reference isn't made). Hence the result is a b c c a c and not a b c c c c.

If you want to change obj1, you'll have to modify it in the change() function directly, you cannot make a reference to it using =. Or create a clone/copy of obj1 using .assign().

For a good article (or well I like it) on objects: https://scotch.io/bar-talk/copying-objects-in-javascript

However be careful when hoisting variables like that, you are technically changing variables outside of the change function. You may want to pass them back and assign them at the same level instead of inside the change function.