2

So I Have this code in JavaScript what is the deffernce between the Line A and Line B

const arr1 = [1,2,3,4,5]

const arr2 = [...arr1]; // Line A
const arr2 = arr1;      // Line B

So I want to know is it the same or there's some difference between the two assignments

  • 1
    In line A, `arr2` is a second, separate object. In line B, `arr1` and `arr2` are both bound to the same object. Modifying one (if you could) would be seen through both names. – Tim Roberts Aug 12 '23 at 03:57
  • [this](https://stackoverflow.com/questions/7486085/copy-array-by-value) could help. – Layhout Aug 12 '23 at 03:58

1 Answers1

3

They are different.

const arr2 = [...arr1]; // Line A

LINE A, copies (shallow copy) each element of the array to arr2.

const arr2 = arr1;      // Line B

LINE B, assigns a reference of arr1 to arr2. Basically, arr1 and arr2 are the same array.

Example

const arr = [1, 2, 3];

const arrA = [...arr];
const arrB = arr;

console.log(arr === arrA); // False
console.log(arr === arrB); // True

arrA[0] = 9;
console.log(arr[0] === arrA[0]); // False
console.log(arr); // [1,2,3]
console.log(arrA); // [9,2,3]

arrB[0] = 9;
console.log(arr[0] === arrB[0]); // True
console.log(arr); // [9,2,3]
console.log(arrB); // [9,2,3]

Shallow Copy

Shallow copy only copies first-level items. For example, if the array contains another array, the inner array is copied, but not the elements of the inner array. So deeper elements are not copied. Please see the code example below:

const arr = [1, 2, [5, 6]];

const arrA = [...arr];
const arrB = arr;

console.log(arr === arrA); // False
console.log(arr === arrB); // True

arrA[0] = 8;
arrA[2][0] = 9;
console.log(arr[2][0] === arrA[2][0]); // True
console.log(arr); // [1, 2, [9, 6]]
console.log(arrA); // [8, 2, [9, 6]]

arrB[0] = 8;
arrB[2][0] = 9;
console.log(arr[2][0] === arrB[2][0]); // True
console.log(arr); // [8, 2, [9, 6]]
console.log(arrB); // [8, 2, [9, 6]]
özüm
  • 1,166
  • 11
  • 23