Is there any difference between the following code(with/without spread operator)?
let result = [];
let arr1 = [1,2,3];
result.push(arr1)
result.push([...arr1])
Unmitigated
91.5k12 gold badges103 silver badges109 bronze badges
1 Answer 1
In the first, without spreading, any modifications to the array at the 0th position in result will result in a change to the original arr1 as well, and vice versa.
If you spread the array while pushing, though, such changes will not occur; the two arrays (one in arr1, one in result[0]) will be completely independent.
let result = [];
let arr1 = [1,2,3];
result.push(arr1)
arr1[1] = 999;
console.log(result);
let result = [];
let arr1 = [1,2,3];
result.push([...arr1])
arr1[1] = 999;
console.log(result);
answered Mar 20, 2021 at 0:33
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
arr1(eg: arr[0]++), and log theresult, you'll see the first gets changed as it's a reference