ES6 way to clone an array
Dhairya Shah
Posted on January 31, 2022
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("π΄ββ οΈ")
console.log(pirateDucks)
// ["π¦", "π¦", "π¦", "π΄ββ οΈ"]
console.log(ducks)
// ["π¦", "π¦", "π¦", "π΄ββ οΈ"] - Original duck array values got changed
Thank you for reading, have a nice day!
Your appreciation is my motivation π
- Follow me on Twitter - @codewithsnowbit
- Subscribe to me on YouTube - Code With SnowBit
Posted on January 31, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024
November 22, 2024