DEV Community

Cover image for ES6 way to clone an array
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

ES6 way to clone an array

Hello Folks πŸ‘‹

What's up friends, this is SnowBit here. I am a young, passionate and self-taught developer and have an intention to become a successful developer.

I hope you enjoy reading this article.


In the olden days, when ES6 was not introduced, we often use the slice() method to clone an array. Now it's the time for ES6, you can use the spread operator to clone an array. It looks pretty neat and right.

const ducks = ["πŸ¦†", "πŸ¦†", "πŸ¦†", "πŸ¦†"]

// Old way
const ducksClone = ducks.slice()

// ES6 way
const ducksCloneES6 = [...ducks]
Enter fullscreen mode Exit fullscreen mode

This is how you clone an array with ES6.

But your crazy mind would have wondered...

Why can't I use = to clone an array?

This is because the array in JavaScript is only referenced values so when you put = and try to clone an array will only copy the reference of the original array to a variable and not an array.

const ducks = ["πŸ¦†", "πŸ¦†", "πŸ¦†"]

const pirateDucks = ducks
const cloneDucks = [...ducks]

console.log(ducks === cloneDucks)
// true -> same memory space

console.log(ducks === pirateDucks)
// false -> new memory space
Enter fullscreen mode Exit fullscreen mode

Some problems arise when using = to clone array

In Javascript, arrays are mutable i.e their state can be modified. So, this might happen when using = πŸ‘‡

const ducks = ["πŸ¦†", "πŸ¦†", "πŸ¦†"]

const pirateDucks = ducks
pirateDucks.push("πŸ΄β€β˜ οΈ")

console.log(pirateDucks)
// ["πŸ¦†", "πŸ¦†", "πŸ¦†", "πŸ΄β€β˜ οΈ"]

console.log(ducks)
// ["πŸ¦†", "πŸ¦†", "πŸ¦†", "πŸ΄β€β˜ οΈ"] - Original duck array values got changed
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, have a nice day!
Your appreciation is my motivation 😊

Top comments (0)