1
function myFunction() {
var a = {};
a.myArray = ["Saab", "Volvo", "BMW"];
var b=a.myArray;
b.push("Chevy");
alert(a.myArray);}

In this above function I have created an object "a" and created an array "myArray". Now I am copying that array in "b" and modifying array "b".But why is it changing a.myArray and how to avoid this?

JRad
  • 11
  • 6
  • 1
    because you're copying a reference to a.myArray into b. You're not creating a new array from a.myArray. – WilomGfx Aug 04 '17 at 20:02

1 Answers1

1

Because you assigned the reference of that array. So you are actually referring the same array with different variable name.

If you want to seperate arrays

var b = a.slice();

Which gives you a new array with same values of your initial array.

slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307