Reputation: 13
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])
Upvotes: 0
Views: 57
Reputation: 370639
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);
Upvotes: 5