ES6 way to clone an array

ES6 way to clone an array

Jan 31, 2022ยท

2 min read

Play this article

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]

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

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("๐Ÿดโ€โ˜ ๏ธ")

// ["๐Ÿฆ†", "๐Ÿฆ†", "๐Ÿฆ†", "๐Ÿดโ€โ˜ ๏ธ"]

// ["๐Ÿฆ†", "๐Ÿฆ†", "๐Ÿฆ†", "๐Ÿดโ€โ˜ ๏ธ"] - Original duck array values got changed

Thank you for reading, have a nice day! Your appreciation is my motivation ๐Ÿ˜Š