-2

I have the following code that copy variable value then change its value.

var a = [{name: 'John Doe'}];
var b = a;

document.write(b[0].name + '<br />');
document.write(a[0].name + '<br /><br />');

b[0].name = 'Jane Doe';

document.write(b[0].name + '<br />');
document.write(a[0].name + '<br />');

But somehow that also change first variable value

How do I make variable A to keep its value?

5
  • 1
    You have to deeply clone a, one way to do it is var b = JSON.parse(JSON.stringify(a)) Commented Jun 1, 2016 at 22:08
  • Possible dupe of: stackoverflow.com/questions/15722433/… Commented Jun 1, 2016 at 22:08
  • Variable a is being passed into b by reference. Since a and b have the same reference, whenever you change anything on one it also changes the other. To prevent this you'll need to do a deep copy of a onto b, copying all of the individual properties. Commented Jun 1, 2016 at 22:08
  • Objects (including Arrays) are assigned by reference in JavaScript. You must manually copy them if you need to maintain two separate .name values. Commented Jun 1, 2016 at 22:09
  • Sorry if its duplicated, I dont know the correct terms when I search the answer before :( Commented Jun 1, 2016 at 22:24

1 Answer 1

1

You are just assigning the a-reference to b. What you may want to do is copying the array so that changes to a are not reflected to b. See this thread for the different assignments in JavaScript.

Take also a look at fastest way to duplicate an array. It's about the speed of different array copy methods. Quick answer is:

var b = a.slice();

The slice() method creates a new array with the same elements than the original one. But be careful it's only a shallow copy.

You could also use the JSON.stringify() and JSON.parse()methods for doing a deep copy.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.