DEV Community

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

Posted on β€’ Originally published at codewithsnowbit.hashnode.dev

3 2

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 😊

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay