0

Recently i heard about something called shallow copying in javascript.

I learned that array.slice(0) will return a shallow copy of the original array (meaning changes made to the original array will be reflected in the duplicate array)..but it is not happening.

original = [1,2];
duplicate = original.slice(); //thinking it as a shallow copy
original.push(3);

now original array has [1,2,3] but duplicate array has [1,2].

As far as i have understood, i thought shallow copy will reflect the changes in both the arrays, hence both array should be same.

But if i do like this, it is happening:

original = [1,2];
duplicate = original; //thinking it as a deep copy
original.push(3);

Are there any great explainers out there???

radio_head
  • 1,306
  • 4
  • 13
  • 28
  • A shallow copy isn't the same thing as an alias. Shallow copy just means that if the list contains references then the copied list will contain the exact same references as opposed to references to copied objects. – John Coleman Jul 11 '17 at 15:32
  • 1
    _"meaning changes made to the original array will be reflected in the duplicate array"_ This is where you've misunderstood - it would be good to see where you learned this from. What it should say is something more like _"changes made to **items in** the original array will be reflected in the duplicate array"_ IE if you had something more complex than just numbers and were updating properties on objects etc. – James Thorpe Jul 11 '17 at 15:32
  • Try this: `orginal = [1,2,[3,4]]; duplicate = original.slice(); original[2].push(5); console.log(duplicate);` – Johan Karlsson Jul 11 '17 at 15:33
  • Possible duplicate of [What is the difference between a deep copy and a shallow copy?](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy) – Liam Jul 11 '17 at 15:38

2 Answers2

0

The .slice() call creates a new array. It's a distinct array from the original, and there's no lasting relationship between the two. Thus after calling .slice() in your first sample of code, the "duplicate" array is on its own. Changes to the original are reflected only in the original array.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

A shallow copy would only apply the elements in the array. After calling .slice() you get a new array. Changes to the elements would be reflected, changes to the array will not.

Nathan Montez
  • 461
  • 3
  • 8