Deep Copy and Shallow Copy in JavaScript

Little deeper into the array methods

Deep Copy and Shallow Copy in JavaScript

Lets start understanding the Deep Copy and Shallow Copy. What do you mean by copy in programming language ? How does the memory gets allocated and behaves when you copy the data ?

It is just assigning the value of one variable to another variable and memory behaves differently when you just assign the value , you expect the original variable to be same but copy changes.

Shallow Copy: When a reference variable is copied into new reference variable using assignment operator , a shallow copy of reference object is created. This means that address of old reference variable is copied to the new reference variable meaning both old and new variable points to the same memory.

Simple assignment creates the shallow copy which shares the same memory and have separate variable name so changing the value of new variable would change the value of another variable as well. image.png

Deep Copy: It makes copy of all the elements of the variable and allocates separate memory for newly created variable and assigns the copied members.

Few example explored image.png

image.png

Have you ever noticed about the slice method applied on the array ? Does it returns the shallow copy or Deep copy of the array?

image.png

Slice methods returns the shallow copy of the array pointing to the same memory. If a reference object changes , the changes visible in both new and original variable.

For strings, numbers and Booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or Boolean in one array do not affect the other array. If a new element is added to either array, the other array is not affected.

Experiment the different array datatypes on different array functions and check does it return a shallow copy ( follows the slice method behavior for all the array function which return the new array ?). Have a fun :)

Hope this makes clear understanding and implementation of the Deep/shallow copy :)