It is important to understand what the = operator does in JavaScript and does not.
The = operator does not copy data.
The = operator creates a new link to the same data.
After running the source code:
var a = $('#some_hidden_var').val(), b = a;
a and b now two different names for the same object.
Any changes you make to the contents of this object will be displayed the same way, whether you refer to it using variable a or variable b . This is the same object.
So, when you later try to โreturnโ b to the original object a with this code:
b = a;
The code actually does nothing, because a and b are the same. The code is the same as if you wrote:
b = b;
which obviously won't do anything.
Why is your new code working?
b = { key1: a.key1, key2: a.key2 };
Here you create a new object with the object literal {...} . This new object does not match your old object. That way, you now set b as a reference to this new object, which does what you want.
To process any arbitrary object, you can use the function to clone the object, for example, specified in Armand's answer, or, since you are using jQuery, just use the $.extend() function . This function will make either a shallow copy or a deep copy of the object. (Do not confuse this with the $().clone() method, which is designed to copy DOM elements, not objects.)
For a shallow copy:
b = $.extend( {}, a );
Or a deep copy:
b = $.extend( true, {}, a );
What is the difference between a shallow copy and a deep copy? A shallow copy is similar to your code that creates a new object with an object literal. It creates a new top-level object containing references to the same properties as the original object.
If your object contains only primitive types, such as numbers and strings, deep copy and shallow copy will do the same. But if your object contains other objects or arrays nested inside it, then a shallow copy does not copy these nested objects, but simply creates links to them. Thus, you may have the same problem with nested objects that you had with your top-level object. For example, given this object:
var obj = { w: 123, x: { y: 456, z: 789 } };
If you make a shallow copy of this object, then the x property of your new object will be the same x object from the original:
var copy = $.extend( {}, obj ); copy.w = 321; copy.xy = 654;
Now your objects will look like this:
// copy looks as expected var copy = { w: 321, x: { y: 654, z: 789 } }; // But changing copy.xy also changed obj.xy! var obj = { w: 123, // changing copy.w didn't affect obj.w x: { y: 654, // changing copy.xy also changed obj.xy z: 789 } };
You can avoid this with a deep copy. A deep copy is repeated in all nested objects and arrays (and Date in the Armand code) to make copies of these objects in the same way that they made a copy of the top-level object. Therefore, changing copy.xy will not affect obj.xy
Short answer: if in doubt, you probably want to get a deep copy.