-3
q = [3,2,4,1]
let copyQ = q;
copyQ.sort(); 
console.log(q) // 1,2,3,4 --------> This doesnt make sense.
console.log(copyQ) //1,2,3,4 -----> This makes sense

I had expected that q would remain the same, i.e unsorted as in line 1, because we had sorted copyQ, but it is not the case.

Whats going on there?

Siddharth Jain
  • 380
  • 1
  • 3
  • 16
  • 3
    You don't copy the array anywhere, 'copyQ' is just a reference to q. `let copyQ = [...q];` – Jared Smith May 11 '20 at 21:47
  • That's an assignment of copy of a reference, not a copy of the object itself. Whereas [...q] iterates over the array and actually copies a reference of all elements of the array into a new array. – user120242 May 11 '20 at 21:50
  • 1
    Why the downvotes without a link to a duplicate? This is a valid newbie question, and a decent well explained answer would go a long way for newbie programmers and their first encounter with references and mutation. – user120242 May 11 '20 at 21:55

1 Answers1

1

sort() function mutates initial array. As soon as your array is copied by link - it is expected. Use spread operator to avoid mutation of initial array. Spread operator will create a copy of your array that will be separate from initial one:

q = [3,2,4,1]
let copyQ = [...q]; 
copyQ.sort(); 
console.log(q)  
console.log(copyQ) 
elvira.genkel
  • 1,303
  • 1
  • 4
  • 11
  • Thank you, but i was under the impression that i am sorting a copy of that array (copyQ), not q. – Siddharth Jain May 11 '20 at 21:48
  • 1
    @SiddharthJain when you use construction let copyQ = q, it doesn't copy the array itself, it copies only link to this array, so both variables q and copyQ contain links to the same area of memory, so both variables are links to the same array. It is concept of reference types in JS – elvira.genkel May 11 '20 at 21:49