0

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])
1
  • 1
    Try changing arr1 (eg: arr[0]++), and log the result, you'll see the first gets changed as it's a reference Commented Mar 20, 2021 at 0:34

1 Answer 1

5

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.