Copy a Variable's Value into Another

Copy a variable's value into another

It's important to understand what the = operator in JavaScript does and does not do.

The = operator does not make a copy of the data.

The = operator creates a new reference to the same data.

After you run your original code:

var a = $('#some_hidden_var').val(),
b = a;

a and b are now two different names for the same object.

Any change you make to the contents of this object will be seen identically whether you reference it through the a variable or the b variable. They are the same object.

So, when you later try to "revert" b to the original a object with this code:

b = a;

The code actually does nothing at all, because a and b are the exact same thing. The code is the same as if you'd written:

b = b;

which obviously won't do anything.

Why does your new code work?

b = { key1: a.key1, key2: a.key2 };

Here you are creating a brand new object with the {...} object literal. This new object is not the same as your old object. So you are now setting b as a reference to this new object, which does what you want.

To handle any arbitrary object, you can use an object cloning function such as the one listed in Armand's answer, or since you're using jQuery just use the $.extend() function. This function will make either a shallow copy or a deep copy of an object. (Don't confuse this with the $().clone() method which is for copying DOM elements, not objects.)

For a shallow copy:

b = $.extend( {}, a );

Or a deep copy:

b = $.extend( true, {}, a );

What's 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 like numbers and strings, a deep copy and shallow copy will do exactly the same thing. But if your object contains other objects or arrays nested inside it, then a shallow copy doesn't copy those nested objects, it merely creates references to them. So you could 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 do a shallow copy of that object, then the x property of your new object is the same x object from the original:

var copy = $.extend( {}, obj );
copy.w = 321;
copy.x.y = 654;

Now your objects will look like this:

// copy looks as expected
var copy = {
w: 321,
x: {
y: 654,
z: 789
}
};

// But changing copy.x.y also changed obj.x.y!
var obj = {
w: 123, // changing copy.w didn't affect obj.w
x: {
y: 654, // changing copy.x.y also changed obj.x.y
z: 789
}
};

You can avoid this with a deep copy. The deep copy recurses into every nested object and array (and Date in Armand's code) to make copies of those objects in the same way it made a copy of the top-level object. So changing copy.x.y wouldn't affect obj.x.y.

Short answer: If in doubt, you probably want a deep copy.

How to copy the value of variable in javascript

var getNum1 = function() {  return 1;};
var getNum2 = function() { return 2;};
var num1 = getNum1();var num2 = getNum2();var result = ((num1 * num2) / 3) - 1;
var executeCopy = function() { var copyhelper = document.createElement("input"); copyhelper.className = 'copyhelper' document.body.appendChild(copyhelper); copyhelper.value = result; copyhelper.select(); document.execCommand("copy"); document.body.removeChild(copyhelper);};
document.getElementById('mybutton').addEventListener('click', function() { executeCopy();
alert("your results has been copied");});
.copyhelper {  position: absolute;}
<button id='mybutton'>Copy to clipboard</button>

Copy value of 1 variable into another variable in UNIX

Easy:

bcd="$abc"

For example:

abc="hello world"

The quotes there are necessary or else it will try to run a command named world with abc in its environment.

Actually, the quotes are not necessary (thanks to 1_CR for pointing this), but I like to add them for readability:

bcd=$abc
bcd="$abc"

They both do the same, exactly what you need.

Lastly, do not use single quotes, or else you will not get the value of the variable:

bcd='$abc'

Error! Now your bcd variable contains the literal value $abc.

Setting a variable equal to another variable

The really short answer to both your questions is that when you make one variable equal to another, a COPY of what's in the first variable is made and stored in the second variable - there is no linkage between the two variables.

But, read on for more details and why it can seem like there is a link in some cases...


JavaScript, like many languages, divides data into two broad categories: value types and reference types. JavaScript value types are its primitives:

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol

When you assign any of these types to a variable, the actual data is stored in that variable and if you set one variable equal to another, a copy (not a linkage) of the primitive is made and stored in the new variable:

var a = 10;  // Store the actual number 10 in the a variable
var b = a; // Store a COPY of the actual number stored in a (10) in the b variable
a = 50; // Change the actual data stored in a to 50 (no change to b here)
console.log("a is: " + a); // 50
console.log("b is: " + b); // 10

Copied variable changes the original?

The line

aux=matriz;

Does not make a copy of matriz, it merely creates a new reference to matriz named aux. You probably want

aux=matriz[:]

Which will make a copy, assuming matriz is a simple data structure. If it is more complex, you should probably use copy.deepcopy

aux = copy.deepcopy(matriz)

As an aside, you don't need semi-colons after each statement, python doesn't use them as EOL markers.

Changing the value of a copy (Date variable) also changes the value of the original (JS)

Please note:

var Uhrzeit = new Date(); Creates a new Date Instance which is an object.

The moment you assign var u = Uhrzeit, this in javascript means that u refers to the same object of date that Uhrzeit refers to.

So variables for objects holds the reference in memory where the object is stored. And by assigned a variable that references an object is simply going to pass that reference to the new variable.

The moment you change either u or Uhrzeit they both reference the same object and they both change the same object.

You must do this instead:

var u = new Date(Uhrzeit); this will create u with the value of Uhrzeit. But they both will now reference different objects in memory.

Ruby: how can I copy a variable without pointing to the same object?

As for copying you can do:

phrase2 = phrase1.dup

or

# Clone: copies singleton methods as well
phrase2 = phrase1.clone

You can do this as well to avoid copying at all:

phrase2 = phrase1.gsub("Hello","Hi")


Related Topics



Leave a reply



Submit