3

consider the following code

var pub_json_general = {"holis":["12/10/2013","12/25/2013","12/26/2013"]};
var holiday = {"holis":["12/02/2013"]};
var pub_json = pub_json_general;
pub_json.holis = $.merge(pub_json.holis,holiday.holis);

After merge, the length of pub_json.holis becomes 4, that's correct. However, when I use firefox debugger, I found that pub_json_general.holis would also be changed, that means pub_json_general and pub_json would always be the same.

So is that "=" operation in javascript is not copying the right-hand side and create the left-hand side to store it but just create the left-hand side which will share the the same memory space with right-hand side?

panda
  • 1,344
  • 3
  • 14
  • 35

3 Answers3

3

Yes, you have explained everything correctly by yourself :)

For reference types, the equality assignment operator assigns reference to the object, it does not clone the object. Therefore when you change one, the other changes too.

RobG
  • 142,382
  • 31
  • 172
  • 209
anar khalilov
  • 16,993
  • 9
  • 47
  • 62
1

You may want to take a look at this question What is the most efficient way to deep clone an object in JavaScript? to solve your problem

Community
  • 1
  • 1
Adassko
  • 5,201
  • 20
  • 37
  • 2
    Everything in JS is pass **by value**. In case of objects, the value happens to be a reference to the object. That is not the same as *pass by reference*! – Felix Kling Nov 27 '13 at 07:57
  • You're right, my bad. It was an unfortunate mental shortcut. I've deleted the misleading sentence – Adassko Nov 27 '13 at 08:12
1

So is that "=" operation in javascript is not copying the right-hand side and create the left-hand side to store it but just create the left-hand side which will share the the same memory space with right-hand side?

This is a very confusing question. If you are trying to understand what is happening in the last statement, here it is:

  1. The expression $.merge(pub_json.holis,holiday.holis) is evaluated. As a result, the contents of holiday.holis are appended to the array residing at pub_json.holis (which is the same array as the one referred to by pub_json_general.holis).

    The result of the expression is the newly altered pub_json.holis array.

  2. The result from 1, pub_json.holis, is assigned to pub_json.holis, which understandably does nothing, and is a non-op.

Community
  • 1
  • 1
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139