0

I was struggling to solve problem, after hours and a few sleeps I found a way around, but I still don't know why this happen.

Here is the code:

var array1 = [];
var array2 = [];

array1 = ["a","b","c","d","f"];
array2 = array1;

for(var i in array2){
  if(array2[i]=="c"){
    array2.splice(i,1);
  }
}

console.log(array1);
console.log(array2); 

When I log both arrays have the same exact values. I am only manipulating the second array, but it refletcs the first one.

Can anybody explain me why this happens ?

  • 1
    It's because you did not duplicate the array. An assignment like that does not create a new array, it makes two variables refer to the same array. – Pointy Aug 01 '22 at 23:44
  • another dupe https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array – Paul Rooney Aug 01 '22 at 23:49
  • it would help you to understand the difference between: 1. copy by reference, 2. shallow copy, 3. deep copy in JS. In your example you are doing copy by reference, you need a shallow or deep copy to avoid modifying the original array. – Bernard Wiesner Aug 01 '22 at 23:58

0 Answers0