If you run following script, something weird will happen, can you tell me ?
const arrayA = [1,2,3]
const duplicate = arrayA
duplicate.push(4)
console.log(duplicate,arrayA)
output for that example will be something like this
[1, 2, 3, 4] [1, 2, 3, 4]
Yes the value from duplicate
array is correct as we expected, but why arrayA
value is changed ?
this happen because we did assignment duplicate = arrayA
and assignment in array is working as reference, so when we try to copy an array using assignment what happen actually is new variable will copy reference to original array and not value of original array.
to handle this problem you can use spread operator to clone arrayA
, spread operator is a new feature that introduce in ES6,
const arrayA = [1,2,3]
const duplicate = [...arrayA]
duplicate.push(4)
console.log(duplicate,arrayA)
output for that example
[1, 2, 3, 4] [1, 2, 3]
Top comments (3)
I wonder how people do it before spread operator exists ?..
I did this 😆
Aah..got it.. thanx