How to duplicate array

Heru Hartanto - Mar 13 '21 - - Dev Community

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)
Enter fullscreen mode Exit fullscreen mode

output for that example will be something like this

[1, 2, 3, 4] [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

output for that example

[1, 2, 3, 4] [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player