rafaelmsantos rafaelmsantos - 25 days ago 6
Javascript Question

Why does my original array get spliced if I splice the cloned array in JavaScript?

I have the following code:

var coords = [
{lat: 39.57904, lng: -8.98094, type: "a"}, // A
{lat: 39.55436, lng: -8.95493, type: "b"}, // B
{lat: 39.56634, lng: -8.95836, type: "c"} // C
];

var travelingOptions = [];

getAllTravelingOptions();

function getAllTravelingOptions(){
coords.forEach((point, pos) => {
let c = coords;
delete c[pos];
console.log(c);
console.log(coords);
});
}


Why is it that variable
c
and
coords
are always the same? If I delete on
c
, it mirrors the action on
coords
. Is this a normal behavior?

Answer

Because of the assignment of c, you get the reference of the array coords.

Any change of coords does effect c, until a new value is assigned to c.

If you make a copy of the array with Array.slice, you get a new array but with the same reference of the objects. When changing one object inside, you are changing the same object with the same reference in c.

var coords = [
         {lat: 39.57904, lng: -8.98094, type: "a"}, // A
         {lat: 39.55436, lng: -8.95493, type: "b"}, // B
         {lat: 39.56634, lng: -8.95836, type: "c"} // C
     ],
     c = coords.slice();

console.log(c);
coords[1].type = 'foo';
console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments