Spread operator Question

Why would you do

let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];

When you can just do

let thisArray = [true, true, undefined, false, null];
let thatArray = [thisArray];

And what does it exactly mean to “spread” an array.

Thanks,

Andrej

because they don’t do the same thing

in the first case you are copying an array

in the second you get [[true, true, undefined, false, null]]
and it is not a copy as if you make changes to thatArray[0] than also thisArray is affected

2 Likes

So the only reason to do (…arr) is so that you get a copy and when you change it it doesnt affect the original?

And I meant to say

let thisArray = [true, true, undefined, false, null];
let thatArray = thisArray;

it is a pretty important thing that it doesn’t affect the original.
Also note that this works to copy only flat arrays, it doesn’t work if you need to copy multi-dimensional arrays, there you would need something different

here a visualization of what’s happening (made with pythontutor):

2 Likes

The syntax has buckets of cool ways its used

1 Like