-2

I passed an array(lets call it originalArr) to a function and then i assigned it to a new variable (lets call it copyArr) and when i changed the contents of the copyArr then the contents of the originalArr also changed example code

justAFunction([1,2,3,4,5,6,7,8]);   
 function justAFunction(originalArr){
      let copyArr = originalArr;
      copyArr.pop();
      copyArr.pop();
      copyArr.pop();
    
    
      
      console.log(originalArr);
    
      }
    output = [ 1, 2, 3, 4, 5 ]

Can some one explain why this is happening

1 Answers1

3

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.

see https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/

Dean Taler
  • 737
  • 1
  • 10
  • 25