When we need to copy an array, we often times used slice. But with ES6, you can also use the spread operator to duplicate an array. Pretty nifty, right ๐คฉ
const sheeps = ['๐', '๐', '๐'];
// Old way
const cloneSheeps = sheeps.slice();
// ES6 way
const cloneSheepsES6 = [...sheeps];
Why Canโt I Use = to Copy an Array?
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.
const sheeps = ['๐', '๐', '๐'];
const fakeSheeps = sheeps;
const cloneSheeps = [...sheeps];
console.log(sheeps === fakeSheeps);
// true --> it's pointing to the same memory space
console.log(sheeps === cloneSheeps);
// false --> it's pointing to a new memory space
Problem with Reference Values
If you ever dealt with Redux or any state management framework. You will know immutability is super important. Let me briefly explain. An immutable object is an object where the state can't be modified after it is created. The problem with JavaScript is that arrays are mutable. So this can happen:
const sheeps = ['๐', '๐'];
const sheeps2 = sheeps;
sheeps2.push('๐บ');
console.log(sheeps2);
// [ '๐', '๐', '๐บ' ]
// Ahhh ๐ฑ , our original sheeps have changed?!
console.log(sheeps);
// [ '๐', '๐', '๐บ' ]
That's why we need to clone an array:
const sheeps = ['๐', '๐'];
const sheeps2 = [...sheeps];
// Let's change our sheeps2 array
sheeps2.push('๐บ');
console.log(sheeps2);
// [ '๐', '๐', '๐บ' ]
// โ
Yay, our original sheeps is not affected!
console.log(sheeps);
// [ '๐', '๐' ]
Mutable vs Immutable Data Types
Mutable:
object
array
function
Immutable:
All primitives are immutable.
string
number
boolean
null
undefined
symbol
Shallow Copy Only
Please note spread only goes one level deep when copying an array. So if you're trying to copy a multi-dimensional arrays, you will have to use other alternatives.
const nums = [[1, 2], [10]];
const cloneNums = [...nums];
// Let's change the first item in the first nested item in our cloned array.
cloneNums[0][0] = '๐ป';
console.log(cloneNums);
// [ [ '๐ป', 2 ], [ 10 ], [ 300 ] ]
// NOOooo, the original is also affected
console.log(nums);
// [ [ '๐ป', 2 ], [ 10 ], [ 300 ] ]
Here's an interesting thing I learned. Shallow copy means the first level is copied, deeper levels are referenced.
Community Input
Array.from is Another Way to Clone Array
const sheeps = ['๐', '๐', '๐'];
const cloneSheeps = Array.from(sheeps);
Top comments (0)