Copying Arrays with Spread and Slice
What you'll learn: How to create independent copies of arrays so changes to one don't affect the other.
Why Copying Matters
When you assign an array to a new variable, JavaScript doesn't create a copy—it creates a reference to the same array in memory. Think of it like two keys to the same house: changes through either key affect the same house. To truly duplicate an array (so you have two separate houses), you need explicit copying techniques.
The Spread Syntax
The spread operator (...) expands an array's elements into a new array:
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] – unchanged!
console.log(copy); // [1, 2, 3, 4]
The Slice Method
Calling slice() without arguments returns a new array containing all elements:
const original = ['a', 'b', 'c'];
const copy = original.slice();
copy[0] = 'z';
console.log(original); // ['a', 'b', 'c'] – unchanged!
console.log(copy); // ['z', 'b', 'c']
Important: Shallow Copies Only
Both methods create shallow copies. They copy the array structure itself, but if the array contains objects or nested arrays, those inner references are still shared:
const original = [{ name: 'Alice' }];
const copy = [...original];
copy[0].name = 'Bob'; // Modifies the shared object!
console.log(original[0].name); // 'Bob' – affected!
For nested structures, you'd need deep copying techniques (a future topic).
Key Takeaway: Use spread syntax ([...array]) or slice() to create shallow copies of arrays, preventing mutations to the copy from affecting the original array structure.