0

let's say I have two javascript arrays, like this:

arrA = [1,2,3]
arrB = [4,5,6]

Is there a way I can reference them with different variable names down then road? If I do this:

arrC = arrA
arrD = arrB

it makes copies of the initial arrays, instead of making a pointer/reference to them. So, if I mess with the value of arrC, arrA isn't updated. Is there a way to get around this?

Thanks.

3
  • 1
    You'll need to provide a sample of code showing your scenario, since arrC = arrA does just make a new reference to the same array. Commented Apr 17, 2013 at 13:32
  • I used below code in firebug: 'arrA = [1, 2, 3]; arrC = arrA; arrC[2] = 9; console.log(arrA)'. It shows that arrA is updated. Commented Apr 17, 2013 at 13:35
  • Yeah, it looks like I was re-assigning my variable name elsewhere in my code. Thanks for the help - I'll accept an answer as soon as it lets me. Commented Apr 17, 2013 at 13:42

2 Answers 2

5

No, it doesn't make a copy. If you change arrC, it will change arrA too.

Try this :

var arrA = [1,2,3];
var arrC = arrA;
arrC.push(26);
console.log(arrA);

You'll see [1, 2, 3, 26] in the console.

The contrary is true : if you want to make a copy, you have to do it explicitly, for example with

var arrC = arrA.slice();
Sign up to request clarification or add additional context in comments.

3 Comments

and if you did want to make a copy, use var copy = arr.splice();
what do you mean? it's the same thing you just edited your answer to include :)
I had edited before, but I was mostly referring to the fact that splice (with a p) doesn't return a copy.
0

Follow this post and Create an array within an object, this is a simple way.

javascript variable reference/alias

1 Comment

1) Don't just link to another question, do it in comment so that somebody can mark it as duplicate. 2) I don't see how it's related. 3) try to gain some rep so that you can comment instead of writing answers that aren't answers. 4) welcome on SO :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.