19

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.

  • It means that `test[0] === shallow_copy[0]`, they refer to the same array object. – Bergi Jul 01 '14 at 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. – pishpish Feb 28 '16 at 11:47

2 Answers2

26

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

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.

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87
  • 9
    That's not a shallow copy. That's not a copy at all. – Niet the Dark Absol Jul 01 '14 at 15:02
  • I may be wrong, please feel free to correct! This is what I learnt from an old experience. – Rutwick Gangurde Jul 02 '14 at 05:59
  • 3
    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 one – elachell Oct 28 '16 at 17:24