Doubt with copy Array

Hi, question on this: Spread

It explains how to copy an array easily using spread … operator

let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
// thatArray equals [true, true, undefined, false, null]
// thisArray remains unchanged, and is identical to thatArray

Just wondering what is the difference or why it is easier than just copy assigning one array to another as follows?

let thisArray = [true, true, undefined, false, null];
let thatArray = thisArray;
console.log(thatArray)
console.log(thisArray)

//Returns
[ true, true, undefined, false, null ]
[ true, true, undefined, false, null ]

In JavaScript, arrays are assigned a reference to a memory location instead of the actual values of the array. This means the above code makes it so thatArray is really the same array as thisArray, so if you make changes to thatArray, you are making changes to thisArray. Using the spread operator creates a shallow copy and puts it into a new array (new memory location), so they would actually be different arrays.

2 Likes

Well, excellent explanation!!! Thanks so much @RandellDawson

Following up on what I said above:

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

thatArray.push('something new');
console.log(thatArray); // [ true, true, undefined, false, null, 'something new' ]
console.log(thisArray); // [ true, true, undefined, false, null, 'something new' ]


let thisArray2 = [true, true, undefined, false, null];
let thatArray2 = [ ...thisArray2 ];

thatArray2.push('something new');
console.log(thatArray2); // [ true, true, undefined, false, null ]
console.log(thisArray2); // [ true, true, undefined, false, null, 'something new' ]
1 Like