0

i wrote a short Codepen where i tried to alter a temporary Array while keeping the original one, but both of my Arrays get altered.

Could someone explain me what the problem is?

var x = ["x"];
abc(x);

function abc(x){
  for(var i = 0; i < 3; i++) {
    var y = x;
    y.unshift("y");
    console.log(y);
    console.log(x);
  }
}

Output:

["y", "x"]
["y", "x"]
["y", "y", "x"]
["y", "y", "x"]
["y", "y", "y", "x"]
["y", "y", "y", "x"]

Thanks in advance.

Frozzo
  • 15
  • 4
  • https://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript looks like if you use array.slice() you can properly copy an array, without the reference. Worth a shot :) – Doug Mar 16 '18 at 12:17
  • `var y = x` is not copying the array. If you want to do a copy (shallow copy) then you need to use `.slice()`. Only then will y not reference x. – Matt Mar 16 '18 at 12:17

2 Answers2

2

There is no internal array. You have only one single array object in the memory. The x and y are only different variables which holds the same reference to the single array instance, because you have assign the value of x to the y which is a reference and that reference is just copied.

If you want to work with the copy of the array you can use slice function.

var x = ["x"];
abc(x);

function abc(x) {

  var y = x.slice();

  for(var i = 0; i < 3; i++) {
    y.unshift("y");
    console.log('Array y: ' + y);
    console.log('Array x: ' + x);
  }
  
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Sorry for the late response and Thanks, this clears up the problem, i didnt know y was also just a reference :). – Frozzo Mar 20 '18 at 06:55
0

Javascript handles objects by reference. So if you write var y = x it does not make a copy of your object but rather a copy of the reference. So when you update y, it updates x at the same time.

If you want to make a copy of your object, you can do the following:

var y = JSON.parse(JSON.stringify(x))
Hammerbot
  • 15,696
  • 9
  • 61
  • 103