Arrays can be copied using spread syntax, introduced in ES6. This is useful because, as with almost everything in JavaScript, a variable containing an array actually only "points" to the array, so if you just try to copy using newArray = oldArray
, it will not make a new copy but instead reference the original array. To illustrate:
let a = [1, 2, 3];
// This won't work.
let b = a;
b[0] = 99;
console.log(...a, ...b); // prints "99 2 3 99 2 3"
// But this will.
let c = [...a]; // before ES6 there was an even uglier way of doing this using "slice", but let's never talk about that
c[0] = 12345;
console.log(...a, ...c); // prints "99 2 3 12345 2 3"
// This won't work.
let b = a;
b[0] = 99;
console.log(...a, ...b); // prints "99 2 3 99 2 3"
// But this will.
let c = [...a]; // before ES6 there was an even uglier way of doing this using "slice", but let's never talk about that
c[0] = 12345;
console.log(...a, ...c); // prints "99 2 3 12345 2 3"