Skip to content
Related Articles

Related Articles

How to Deep clone in JavaScript?
  • Last Updated : 29 Oct, 2020

In general, cloning means copying one value to another. In JavaScript, we do cloning i.e. copying one value to another using JavaScript. To be more precise they are two types of cloning in JavaScript. As a programmer, it might be a beginner or veteran he/she should be able to know the differences between Deep clone and shallow clone. As this article is about Deep clones we will study detail about Deep clones. Cloning is a concept that can happen in any data type i.e., it might be a primitive data type (like string, number) or composite data types like arrays and JavaScript. So in order to master it, we need to be clear with the foundation.

Deep Clone: Deep clone is a technique that is used to duplicate everything whenever we are cloning arrays, JavaScript in order to avoid data loss.

Example 1: As in this example, the data is becoming corrupted if we change one object value then it is reflecting in other objects also that is the reason in order to avoid this problem we use Deep Clone.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    var student1 ={ 
        name : "Manish",
        company : "Gfg"
  
    }
  
    var student2 =  student1  ;
  
    student1.name = "Rakesh"
      
    console.log("student 1 name is",student1.name)
    console.log("student 2 name is ",student2.name);
</script>

chevron_right


Output:



Example 2: Using Spread Operator

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    var student1 ={  
    name : "Manish",
    company : "Gfg"
  
    }
  
    var student2 =  { ...student1 } ;
  
    student1.name = "Rakesh"
  
    console.log("student 1 name is",student1.name)
    console.log("student 2 name is ",student2.name);
</script>

chevron_right


Output:
 

Example 3: Using Object.assign()

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    var student1 ={ 
    name : "Manish",
    company : "Gfg"
    }
  
    var student2 = Object.assign( {} ,student1) ;
  
    student1.name = "Rakesh"
  
    console.log("student 1 name is",student1.name)
    console.log("student 2 name is ",student2.name);
</script>

chevron_right


Output:

Example 4: Using Json.parse and Json.stringfy

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    var student1 ={ 
    name : "Manish",
    company : "Gfg"
  
    }
  
    var student2 = JSON.parse(JSON.stringify(student1))
  
    student1.name = "Rakesh"
  
    console.log("student 1 name is",student1.name)
    console.log("student 2 name is ",student2.name);
</script>

chevron_right


Output:

Conclusion: We can use all of these approaches to make sure that the data is safe and doesn’t get mutate when we change in one object.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :