2

Consider:

let myArray = [1, 2, 3];
let myArray2 = myArray;
let myArray3 = [...myArray];

What is the difference between the assignments for myArray2 and myArray3? Is myArray2 a reference to the same memory as myArray (so if myArray.shift(), the value of myArray2 also changes), whereas myArray3 is a copy of myArray?

Clarification: I understand [...myArray] creates a copy of the array. I'm not clear if myArray2 = myArray also creates a copy, or creates a a second reference to the same array, so changing the array via one will be reflected when getting the value via the other.

David Burson
  • 2,465
  • 5
  • 28
  • 49
  • `let myArray = [1, 2, 3]; let myArray2 = myArray; let myArray3 = [...myArray]; myArray[2] = "HI"; console.log("myArray2", myArray2) console.log("myArray3", myArray3)` – epascarello Mar 22 '18 at 16:23
  • https://stackoverflow.com/questions/33092646/i-want-mean-in-javascript-three-point-operator – alvaro fvr Mar 22 '18 at 16:33
  • 2
    don't think that this is the same question as the one that is marked as duplicate of – Calvin Nunes Mar 22 '18 at 16:33
  • 1
    @Quentin, this is not a duplicate. This is more about spread operator and deep copy : `let myArray = [1, 2, [0,0],{a:1}]; let myArray2 = myArray; let myArray3 = [...myArray]; myArray[2]=[1,1]; myArray[3].a=5; myArray[4]=6; console.log(myArray,myArray2,myArray3);` – scraaappy Mar 22 '18 at 16:56
  • "*I'm not clear if `myArray2 = myArray` also creates a copy, or creates a a second reference to the same array, so changing the array via one will be reflected when getting the value via the other*" - Then write some code and *test* it. Can easily be done in a web browser console in the about same amount of time it took you to edit your answer! – robinCTS Mar 23 '18 at 00:15
  • Thanks to all for the comments. I now have an answer. I believe this to be a different question than the ones referenced, but I cannot add an answer because this question has been closed. So, for easy reference, here's what I found helpful: let myArray = [1, 2, [0,0],{a:1}]; let myArray2 = myArray; let myArray3 = [...myArray]; myArray[2][0]=99; myArray[2]=[1,1]; myArray[2][0]=22; myArray[3].a=5; myArray[4]=6; console.log(myArray); console.log(myArray2); console.log(myArray3); yields: [1, 2, [22, 1], Object {a=5}, 6] [1, 2, [22, 1], Object {a=5}, 6] [1, 2, [99, 0], Object {a=5}] – David Burson Mar 23 '18 at 14:44

0 Answers0