Difference between assignment and unpacking intto one array to another

52 Views Asked by At

I have this code in JavaScript what is the difference between the lines A and B ?

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

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

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

1

There are 1 best solutions below

0
özüm On BEST ANSWER

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]]