Frozzo
Frozzo

Reputation: 15

Javascript ES5 unshift / push alters original Array instead of internal Array

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.

Upvotes: 0

Views: 406

Answers (2)

Hammerbot
Hammerbot

Reputation: 16344

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))

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68645

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);
  }
  
}

Upvotes: 2

Related Questions