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?
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?
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.
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]; To create a copy, do this:
var q = [1, 2, 3]; var w = q.slice(); Source: https://ru.stackoverflow.com/questions/596773/
All Articles