What is the difference between a shallow copy and a deep copy with JavaScript arrays? [duplicate]

According the MDN documentation calling array.slice() will create a shallow copy of the array.

See this MDN link for slice().

However, if I run a simple test as such in the console:

var test = [[1,2,3],7,8,9];
var shallow_copy = test.slice();

and inspect shallow_copy, I can see that the entire 2 dimensional array appears to be copied over.

What is the difference between a shallow copy and a deep copy? If I were to guess, I would have called this a deep copy.


To see the difference, try:

shallow_copy[0][2] = 4;
console.dir(test);

You'll see that test has been modified! This is because while you may have copied the values to the new array, the nested array is still the same one.

A deep copy would recursively perform shallow copies until everything is a new copy of the original.


Basically you're just getting a reference to the original variable/array. Changing the reference will also change the original array. You need to loop over the values of the original array and form a copy.

Consider this example:

var orig = {  a: 'A', b: 'B', c: 'C' };

Let's say you want to create a duplicate of this, so that even if you change the original values, you can always return to the original.

I can do this:

var dup = orig; //Shallow copy!

If we change a value:

dup.a = 'Apple';

This statement will also change a from orig, since we have a shallow copy, or a reference to var orig. This means, you're losing the original data as well.

But, creating a brand new variable by using the properties from the original orig variable, you can create a deep copy.

var dup = { a: orig.a, b: orig.b, c: orig.c }; //Deep copy!

Now if you change dup.a, it will only affect dup and not orig.