1
var arr = new Array();
arr[0] = "a";
var ob = new Object();
ob.prop = arr;
ob.prop[0] = "b";
//Console log arr[0] returns b

for some reason, the arr array is being changed when I change ob.prop ?

What am I missing?

1
  • You've assigned a reference to the same Array. Commented Mar 13, 2013 at 23:15

2 Answers 2

1

As the system pointed out, ob.prop = arr is basically just giving another name for accessing the object referenced by arr. So when you modify ob.prop you are modifying the same object that arr also refers to.

EDIT: For copying an array take a look at this question:

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

1 Comment

So how would I go about creating a copy of arr instead of a reference to it?
1

As Jorge mentioned, this is happening because obj.prop is just a reference to arr, so arr and obj.prop will point to the same place in memory. So if you change either, the value in memory (which the other is pointing to) changes, thus changing both.

If you're looking to avoid this you need to do a deep copy. This will copy the values of the array into a new array, which obj.prop will point at.

There is a walk-through of how to do this in javascript here.

Comments

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.