Why it happens?

var q = [1, 2, 3]; var w = q; q[0] = 0; console.log(w) // [0, 2, 3] 

Those. the array is not copied and just creates a link to the same array. Why?

3 answers 3

Because almost all languages ​​work this way. It is much cheaper when copying objects to copy a link (4 or 8 bytes in size) than to copy each object in the array, and each object in turn copies all its properties, which can also be objects or arrays. It would take a lot of time.

  • That is, the question of optimization. In general, I have been working with js for a long time, but for some reason I haven’t stumbled upon this behavior before - Vasya Shmarovoz
  • one
    @VasyaShmarovoz apparently little work. Because this is the default behavior. It does not apply to "simple types", such as strings, numbers, and logical values, which are copied by value. - DreamChild

Objects in JS (which also include arrays) are copied into a variable "by reference". To avoid this, it is necessary to clone an array (the new array will have a new internal link). For this you can use the methods:

 var w = q.slice(); 

Or more modern method ES6

 var w = [...q]; 
  • Thanks, helpful - Vasya Shmarovoz

To create a copy, do this:

 var q = [1, 2, 3]; var w = q.slice();