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

Go To StackoverFlow.com

16

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.

2014-07-01 14:25
by NoName
It means that test[0] === shallow_copy[0], they refer to the same array object - Bergi 2014-07-01 15:11
I find the use of the word 'shallow' and 'deep' totally confusing in JavaScript documentation as it is already said that objects are never copied. When it explicitly reads 'shallow' I would expect all elements to be references to the same thing (including non objects such as numbers), but it only applies to objects, which are already stated never to be copied - destoryer 2016-02-28 11:47


23

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.

2014-07-01 14:27
by Niet the Dark Absol


1

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.

2014-07-01 14:41
by Rutwick Gangurde
That's not a shallow copy. That's not a copy at all - Niet the Dark Absol 2014-07-01 15:02
I may be wrong, please feel free to correct! This is what I learnt from an old experience - Rutwick Gangurde 2014-07-02 05:59
This is just passing the reference not shallow or deep copy. Look at the best answer at: http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy for the difference between shallow and deep copy. Also what you refer as "deep copy" in your example is actually a shallow on - elachell 2016-10-28 17:24
Ads