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?

user2123244
  • 99
  • 1
  • 4

2 Answers2

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();
Community
  • 1
  • 1
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
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.

Nick Mitchinson
  • 5,452
  • 1
  • 25
  • 31