0

When do variables made from arrays act as pointers to the array and when do they act as copies of the array?

For instance if I have an array named Array1

a1=Array1; 

is a1 a copy or a pointer to the array.

If I modify a1 will it also modify Array1. By modify I mean change a value, push something into the array, sort, or any other way you could modify an array.

thanks,

Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
asked Mar 15, 2013 at 21:52
1
  • 1
    x = [1,2,3]; y = x; y[0] = 7; console.log(x) will output 7,2,3. arrays in JS are objects, and when you copy an object via newobj = origobj, you're just creating a reference. you need to CLONE the array object to create a truly independent copy. Commented Mar 15, 2013 at 21:56

2 Answers 2

1

Variable assignment in JavaScript never makes copies for non-primitives (everything that isn't a value).

Assignment for all non-values copies references.

answered Mar 15, 2013 at 21:56
Sign up to request clarification or add additional context in comments.

Comments

1

A variable in javascript holds a reference to the array.

If you copy the variable value with arr2 = arr1, you copy the reference to the same array. So any change to arr2 is a change to arr1.

If you want another variable to hold a reference to a copy, so that you may change the second array without changing the first one, use slice :

var arr2 = arr1.slice();
answered Mar 15, 2013 at 21:54

2 Comments

I don't remember why exactly, but I think you want that to be arr1.slice(0)
You may also want to note that .slice() only creates a shallow copy of the array.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.