0

im a JS beginner and I'm a bit confused of this code:

let array = ["string1", "string2"]
let arrayCopy = array
array[0] = "changedString"
console.log(arrayCopy)
// Returns Array ["changedString", "string2"]

Why is the assignment of Array also mutating the copy?

  • 1
    Because it’s not a copy, it’s assignment so it’s the same array – Sami Kuhmonen Apr 05 '21 at 11:02
  • You can find more here https://www.codeproject.com/Questions/1163106/Changing-an-array-in-javascript-affect-copies-of-t – Surjeet Bhadauriya Apr 05 '21 at 11:06
  • `arrayCopy` is a copy of the reference i.e. both `array` and `arrayCopy` refer to the same array of string in the memory and it is normal that mutation done through `array` will be visible also from `arrayCopy` because both variables refer to the same array object. More on this topic here: https://javascript.info/object-copy – Anton Kovachev Apr 05 '21 at 11:07

0 Answers0