Shallow and Deep Copying in JS

·

2 min read

  • There is no any funda of deep or shallow copy applicable for the primitive data types as they are immutable in javascript . Source

  • Deep Copy and Shallow Copy Concept is applicable only for reference variable .

    Shallow Copy

    • Shallow copy is also identified by pass by reference in other programming languages.
    • When you make a copy of variable(original source) into another variable(new source) by using assignment operator(=) on that time only the reference address(memory address) of the original variable is copied by into another variable and not the actual value(objects, array, etc).
  • At last, both variables refer to the same value. So when you make any changes in the new variable it will also mutate(Change) the original variable.

What's the problem here ?

Javascript does a shallow copy by default for the non-primitive data type(Object, Array, Functions, Math, etc. So Copied version is still connected to Source version that why we need to find some works around to safely copy the data Safely .

Deep copy

Deep copy is also identified by pass by value in other programming languages. What is a Deep copy? When you make a copy of variable(original source) into another variable(new source) by using assignment operator(=) on that time all the values(objects, array, etc) along with the reference address(memory address) of the original variable is copied by into another variable.

  • At last, both variables refer to the different referenced values. So when you make any changes in the new variable it won’t mutate the original variable.