How to deep copy an array in Javascript

Hoang Ha
2 min readJan 13, 2021

Firstly, array is object in Javascript.

Array is object

So if you clone it like below,

This results in two variables referring to the same array object. If you change one of them, another will change too.

Changing new array will affect original array

What we can do is using spread operator.

Copy using spread operator

The slice() method does pretty much the same,

Copy using slice()

These methods work well for arrays that stores literal value. How about array that store reference type elements?

Pushing new object to new array won’t change the original array

Great, pushing new element to new array does not change the original array. How about changing the value of the element.

changing object in the copied array affects the original array’s object

Oops! So it is not really deep copy anyway since the original array get changed. This is because although the new array and old array are 2 separate objects, the elements inside them remain the same reference.

Solution is serializing the original array to JSON string and then constructing the new array from there.

Serializing and de-serializing array to make a deep copy

In short, we can use spread operator or slice() to deep copy an array that stores value type element but with reference type array , extra work is needed.

--

--