{"id":4182,"date":"2022-09-12T23:00:39","date_gmt":"2022-09-13T04:00:39","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=4182&#038;preview=true&#038;preview_id=4182"},"modified":"2022-09-12T23:11:23","modified_gmt":"2022-09-13T04:11:23","slug":"javascript-shallow-vs-deep-copy","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/","title":{"rendered":"Difference Between Shallow Copy and Deep Copy in JavaScript"},"content":{"rendered":"\n<p>If you have been programming in Javascript for some time now, you have likely worked with copies even if you might not have realized it. The concept of copying might not seem important until you change a value in the &#8216;copy object&#8217; and expect the &#8216;original object&#8217; to remain the same. To effectively work with copies in your projects, Javascript includes support for shallow and deep copies.<\/p>\n\n\n\n<p><strong>A shallow copy means some (if not all) of the copied values are still connected to the original. Any operation carried on the &#8216;copied&#8217; version might affect the original. On the other hand, a deep copy means all copied values are disconnected from the original. Any operation carried on the &#8216;copied&#8217; version will not in any way not affect the original.<\/strong><\/p>\n\n\n\n<p>You have probably heard of the principle in functional programming philosophy &#8211; &#8220;<a href=\"https:\/\/www.infoworld.com\/article\/3613715\/what-is-functional-programming-a-practical-guide.html\" target=\"_blank\" rel=\"noopener\">you should not modify the existing data<\/a>.&#8221; To achieve that, you need to know how to safely copy data while avoiding pitfalls. To get started, this post will first give you a detailed refresher on Javascript data types since they have a huge influence on how you copy values.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Javascript_Data_Types\" >Javascript Data Types<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Primitive_Data_Types\" >Primitive Data Types<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Non-primitive_Data_Types\" >Non-primitive Data Types<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Copying_Primitive_Values\" >Copying Primitive Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Copying_Non-Primitive_Values\" >Copying Non-Primitive Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Shallow_Copy\" >Shallow Copy<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Deep_Copy\" >Deep Copy<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Un-nested_Objects\" >Un-nested Objects<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#The_Spread_Operator_%E2%80%A6\" >The Spread Operator (&#8230;)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#The_Objectassign_method\" >The Object.assign() method<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Nested_Objects\" >Nested Objects<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Partial_Deep_Copy\" >Partial Deep Copy<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#JSONParseJSONstringify_Method\" >JSON.Parse(JSON.stringify()) Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Using_Lodash_to_Perform_a_Deep_Copy\" >Using Lodash to Perform a Deep Copy<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Javascript_Data_Types\"><\/span>Javascript Data Types<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There are two main data types in Javascript. <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Data_structures\" target=\"_blank\" rel=\"noopener\">Primitive data types and Non-primitive data types<\/a>. The main difference between the two is how the values are stored in memory. Primitive values are stored by value while non-primitive values are stored by reference.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Primitive_Data_Types\"><\/span>Primitive Data Types<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Below is a list of all primitive types in Javascript.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>String: Store alphanumeric characters and symbols<\/li><li>Boolean: Hold a &#8216;true&#8217; or &#8216;false&#8217; value.<\/li><li>Number: Hold numbers and decimals.<\/li><li>Undefined: This means a variable has been created but hasn&#8217;t been assigned a value.<\/li><li>Null: It&#8217;s explicitly set by a developer to mean &#8217;empty&#8217; or &#8216;nothing.&#8217;<\/li><li>Symbol<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Non-primitive_Data_Types\"><\/span>Non-primitive Data Types<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>There is only one non-primitive data type in Javascript &#8211; &#8216;<strong>Object<\/strong>.&#8217; However, <strong>arrays<\/strong> also fall into this category as they are regarded as Objects in Javascript.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Copying_Primitive_Values\"><\/span>Copying Primitive Values<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When working with primitive values in Javascript, copying is not an issue since these values exist only once and refer to a single value in memory. Primitive values are tightly coupled with the variable they are assigned to. Therefore, if you make a copy &#8211; it is a <strong>deep (real) copy<\/strong>. Look at the examples below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let log = console.log;\n\nlet a = 5;\nlet b = a;\n\nb = 8 \/\/Re-assign the value of 'b'\n\nlog(a)\nlog(b)\n\n\/*Output:\n5\n8<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">The line <code>let a = 5;<\/code> creates a variable <code>a<\/code> and allocates space in memory to hold its value. In this case, the value is 5. The line <code>let b = a;<\/code> creates another variable <code>b<\/code> and allocates its space in memory to store its value. The value, in this case, is &#8216;<em>the value stored by variable a<\/em>&#8216; which is 5.<\/p>\n\n\n\n<p class=\"language-javascript has-luminous-vivid-amber-background-color has-background\"><strong>Note<\/strong>: The variable <code>b<\/code> is assigned the value of <code>b<\/code>, not the address of <code>a<\/code> in memory.<\/p>\n\n\n\n<p class=\"language-javascript\">When you reassign the value of <code>b<\/code> in the line <code>let b = 8;<\/code>, only the value of <code>b<\/code> is changed. The value of <code>a<\/code> remains the same. <\/p>\n\n\n\n<p class=\"language-javascript\">From the examples discussed in this section, it&#8217;s clear that when working with primitive values, any copy operation will result in a <strong>deep copy<\/strong>. The concept of shallow and deep copies mainly applies when dealing with objects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Copying_Non-Primitive_Values\"><\/span>Copying Non-Primitive Values<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When working with primitives, you learned in the previous section that primitive values are tightly coupled with their assigned variables. Objects, on the other hand, are stored by stored\/ held by reference. This &#8220;<em>by reference<\/em>&#8221; is what mainly brings up the issue of the <strong>shallow<\/strong> and <strong>deep<\/strong> copy.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Shallow_Copy\"><\/span>Shallow Copy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Take a look at the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let log = console.log;\n\n\/\/Create the first object, studentOne\nconst studentOne = {\n  firstName:\"Jane\",\n  lastName:\"Doe\",\n  age:25\n}\n\n\/\/Create a copy of studentOne object\nlet studentTwo = studentOne\n\n\/\/Reassign the value of firstName in studentTwo object\nstudentTwo.firstName=\"John\"\n\nlog(studentOne)\nlog(studentTwo)\n\n\/*Output:\n{ firstName: 'John', lastName: 'Doe', age: 25 }\n{ firstName: 'John', lastName: 'Doe', age: 25 }<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">The code snippet above is quite simple. You first created a <code>studentOne<\/code> object with several key-value pairs. Next, you made a copy of the <code>studentOne<\/code> object using the <a href=\"https:\/\/www.w3schools.com\/js\/js_assignment.asp\" target=\"_blank\" rel=\"noopener\">assignment operator (=)<\/a> to create a second object called <code>studentTwo<\/code>. Lastly, you reassigned the value of <code>firstName<\/code> in the <code>studentTwo<\/code> object.<\/p>\n\n\n\n<p class=\"language-javascript\">When you log the two objects, you will notice that the value of <code>firstName<\/code> changed both in the &#8216;copy&#8217; and the &#8216;original&#8217; object. That&#8217;s because when you created a copy of the <code>studentOne<\/code> object in the line let <code>studentTwo = studentOne<\/code>, you only assigned <code>studentTwo<\/code> the address of <code>studentOne<\/code>. <\/p>\n\n\n\n<p class=\"language-javascript\">In short, both <code>studentOne<\/code> and <code>studentTwo<\/code> are pointing to the same address in the memory. This is a perfect illustration of a <strong>shallow copy<\/strong>. Although we created a new object (studentTwo), its values are still connected to the original object (studentOne).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Deep_Copy\"><\/span>Deep Copy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There are different ways that you can use to perform a deep copy in Javascript. However, you will notice that these methods work differently with nested and un-nested objects. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Un-nested_Objects\"><\/span>Un-nested Objects<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>When working with <strong>non-nested<\/strong> objects (objects that don&#8217;t have other objects as values), you can use the following methods to perform a deep copy.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The spread operator (&#8230;)<\/li><li>The Object.assign() method<\/li><\/ul>\n\n\n\n<p>Take a look at the code snippets below.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Spread_Operator_%E2%80%A6\"><\/span>The Spread Operator (&#8230;)<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>The code below illustrates how to carry out a deep copy with the spread operator.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let log = console.log;\n\n\/\/Create the first object\nconst studentOne = {\n  firstName:\"Jane\",\n  age:25,\n}\n\n\/\/Make a copy of studentOne object using the SPREAD operator\nconst studentTwo = {...studentOne}\n\n\/\/Re-assign the value of firstName in studentTwo object\nstudentTwo.firstName=\"John\"\nlog(studentOne)\nlog(studentTwo)\n\n\/*Output:\n{ firstName: 'Jane', age: 25 }\n{ firstName: 'John', age: 25 }<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Here, you can see that the value of <code>firstName<\/code> in the original object did not change even after reassigning it using the copied object.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Objectassign_method\"><\/span>The Object.assign() method<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>The code below illustrates how to carry out a deep copy with the <code>Object.assign()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let log = console.log;\n\n\/\/Create the first object\nconst studentOne = {\n  firstName:\"Jane\",\n  age:25,\n}\n\n\/\/Make a copy of studentOne object using the Object.assign() method\nconst studentTwo = Object.assign({},studentOne)\n\n\/\/Re-assign the value of firstName in studentTwo object\nstudentTwo.firstName=\"John\"\nlog(studentOne)\nlog(studentTwo)\n\n\/*Output:\n{ firstName: 'Jane', age: 25 }\n{ firstName: 'John', age: 25 }<\/code><\/pre>\n\n\n\n<p>Similar to using the spread operator, only the value of firstName in the copied object change. The original object was not affected.<\/p>\n\n\n\n<p>Up to this point, you have learned how to create deep copies when working with un-nested objects. In the next section, you will learn how to work with nested objects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Nested_Objects\"><\/span>Nested Objects<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: The <code>spread<\/code> operator and the <code>Object.assign()<\/code> method will only do a partial copy when used with nested objects.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Partial_Deep_Copy\"><\/span>Partial Deep Copy<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Take a look at the object below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const studentOne = {\n  firstName:\"Jane\",\n  age:25,\n  skill:{\n    primary:\"Web developer\",\n    secondary:\"DevOps\"\n  }\n}<\/code><\/pre>\n\n\n\n<p>Make a copy using the spread operator.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/Make a copy of studentOne object using the SPREAD operator\nconst studentTwo = {...studentOne}\n\n\/\/Re-assign the value of firstName in studentTwo object\nstudentTwo.firstName=\"John\"\nstudentTwo.skill.primary=\"cybersecurity\"\nlog(studentOne)\nlog(studentTwo)\n\n\/*Output:\n{\n  firstName: 'Jane',\n  age: 25,\n  skill: { primary: 'cybersecurity', secondary: 'DevOps' }\n}\n{\n  firstName: 'John',\n  age: 25,\n  skill: { primary: 'cybersecurity', secondary: 'DevOps' }\n}<\/code><\/pre>\n\n\n\n<p>Make a copy using the Object.assign() method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/Make a copy of studentOne object using the Object.assign() operator\nconst studentTwo = Object.assign({},studentOne)\n\n\/\/Re-assign the value of firstName in studentTwo object\nstudentTwo.firstName=\"John\"\nstudentTwo.skill.primary=\"cybersecurity\"\nlog(studentOne)\nlog(studentTwo)\n\n\/*Output:\n{\n  firstName: 'Jane',\n  age: 25,\n  skill: { primary: 'cybersecurity', secondary: 'DevOps' }\n}\n{\n  firstName: 'John',\n  age: 25,\n  skill: { primary: 'cybersecurity', secondary: 'DevOps' }\n}<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">When you look at the output of the two code snippets above, you will notice that after reassigning the values <code>firstName<\/code> and <code>skill.primary<\/code> using the copied object, the value of <code>skill.primary<\/code> changed in both the &#8216;copied&#8217; object and the &#8216;original&#8217; object. The <code>firstName<\/code> value only changed in the &#8216;copied&#8217; object.<\/p>\n\n\n\n<p>That&#8217;s because the spread operator and the <code>Object.assign()<\/code> method only did a partial deep copy. The values <code>firstName<\/code> and <code>age<\/code> were deeply copied while the nested object <code>skill<\/code> was shallowly copied.<\/p>\n\n\n\n<p>So, what&#8217;s the best solution for the <strong>partial deep copy<\/strong> problem?<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"JSONParseJSONstringify_Method\"><\/span>JSON.Parse(JSON.stringify()) Method<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>The JSON.parse(JSON.stringify(object)) methods are used to solve the issue of partial deep copy that arise with the spread operator and the Object.stringify() method. Together, these methods first stringify the object to a JSON string and then parse it to an object.<\/p>\n\n\n\n<p>Take a look at the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let log = console.log;\n\n\/\/Create the first object\nconst studentOne = {\n  firstName:\"Jane\",\n  age:25,\n  skill:{\n    primary:\"Web developer\",\n    secondary:\"DevOps\"\n  }\n}\n\n\/\/Make a copy of studentOne object using the JSON methods\nconst studentTwo = JSON.parse(JSON.stringify(studentOne))\n\n\/\/Re-assign the value of firstName in studentTwo object\nstudentTwo.firstName=\"John\"\nstudentTwo.skill.primary=\"cybersecurity\"\nlog(studentOne)\nlog(studentTwo)\n\n\/*Output:\n{\n  firstName: 'Jane',\n  age: 25,\n  skill: { primary: 'Web developer', secondary: 'DevOps' }\n}\n{\n  firstName: 'John',\n  age: 25,\n  skill: { primary: 'cybersecurity', secondary: 'DevOps' }\n}<\/code><\/pre>\n\n\n\n<p>In the output above, you can see that after the reassignment, only the &#8216;copied&#8217; object values changed. The &#8216;original&#8217; object was not affected. That is a perfect illustration of a deep copy in Javascript. The copied values are not in any way connected to the original values.<\/p>\n\n\n\n<p>However, there is a catch! Take a keen look at the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let log = console.log;\n\n\/\/Create the first object\nconst originalTask = {\n  name:\"Learn React\",\n  duration: function(params){\n    return \"24hrs\"\n  },\n  date:new Date(),\n}\n\n\/\/Make a copy of studentOne object using the SPREAD operator\nconst copiedTask = JSON.parse(JSON.stringify(originalTask))\n\nlog(\"Original Date = \"+typeof(originalTask.date))\nlog(\"Copied Date = \"+typeof(copiedTask.date))\nlog(originalTask)\nlog(copiedTask)\n\n\/*Output:\nOriginal Date = object\nCopied Date = string\n{\n  name: 'Learn React',\n  duration: &#91;Function: duration],\n  date: 2022-09-12T08:07:01.163Z\n}\n{ name: 'Learn React', date: '2022-09-12T08:07:01.163Z' }<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In the code above, you can see the <code>originalTask<\/code> object which includes two methods as its values. However, there are two interesting things that happen when you make a copy of the <code>originalTask<\/code> object using the JSON.parse &#8211; JSON.stringify methods.<\/p>\n\n\n\n<ul class=\"language-javascript wp-block-list\"><li>The function in the &#8216;duration&#8217; key inside <code>originalTasks<\/code> is missing\/ lost in the <code>copiedTask<\/code>.<\/li><li>Using the &#8216;typeof&#8217; operator, you will notice that the &#8216;date&#8217; in the <code>originalTask<\/code> is an object but the &#8216;date&#8217; in the <code>copiedTask<\/code> is a string.<\/li><\/ul>\n\n\n\n<p class=\"language-javascript\">Although you have made a deep copy of the <code>originalTask<\/code> object, the resulting object (<code>copiedTask<\/code>) is lacking several key features which might result in errors in your application.<\/p>\n\n\n\n<p>So, what&#8217;s the solution?<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Lodash_to_Perform_a_Deep_Copy\"><\/span>Using Lodash to Perform a Deep Copy<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"language-javascript\">Lodash is a popular Javascript library that comes with various methods that you can utilize in your program. One such method is the <code>cloneDeep()<\/code> function which you can use to deeply clone\/copy an object including non-serializable properties that were not supported by the JSON.parse &#8211; JSON.stringify methods.<\/p>\n\n\n\n<p>Use the command below to install the Lodash library.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>npm install lodash<\/code><\/pre>\n\n\n\n<p>The code below shows you how to perform a deep copy using Lodash.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const _ = require(\"lodash\")\nlet log = console.log;\n\n\/\/Create the first object\nconst originalTask = {\n  name:\"Learn React\",\n  duration: function(params){\n    return \"24hrs\"\n  },\n  date:new Date(),\n}\n\n\/\/Make a copy of studentOne object using the Lodash cloneDeep() method\nconst copiedTask = _.cloneDeep(originalTask)\n\nlog(\"Original Date = \"+typeof(originalTask.date))\nlog(\"Copied Date = \"+typeof(copiedTask.date))\nlog(originalTask)\nlog(copiedTask)\n\n\/*Output:\nOriginal Date = object\nCopied Date = object\n{\n  name: 'Learn React',\n  duration: &#91;Function: duration],\n  date: 2022-09-12T09:14:04.703Z\n}\n{\n  name: 'Learn React',\n  duration: &#91;Function: duration],\n  date: 2022-09-12T09:14:04.703Z\n}<\/code><\/pre>\n\n\n\n<p>From the output above, you can see all the issues that were occurring with the JSON.parse &#8211; JSON.stringify methods are solved. The &#8216;duration&#8217; function present in the <code>originalTask object<\/code> is also available in the <code>copiedTask<\/code> object. The type of &#8216;date&#8217; is an object in both <code>originalTask<\/code> and <code>copiedTask<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This post has given you a comprehensive guide on carrying out a deep copy and shallow copy in Javascript. Below is a summary of methods that you can use to perform a deep copy for different scenarios.<\/p>\n\n\n\n<p>Making a deep copy of un-nested objects.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Spread Operator<\/li><li>Object.stringify<\/li><\/ul>\n\n\n\n<p>Making a deep copy of nested objects.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>JSON.parse(JSON.stringify()) methods : Remember, this will not work for objects that have methods as values.<\/li><li>Third-party libraries (i.e Lodash)<\/li><\/ul>\n\n\n\n<p><strong>Was this article helpful? Do you have any comments or suggestions?<\/strong><\/p>\n\n\n\n<p>Let us know by replying on Twitter of\u00a0<a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">Become A Better Programmer<\/a>\u00a0or to my\u00a0<a href=\"https:\/\/twitter.com\/tonygidraph\" target=\"_blank\" rel=\"noreferrer noopener\">personal Twitter account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">Be careful with simply copying the values of a variable in <a href=\"https:\/\/twitter.com\/hashtag\/javascript?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#javascript<\/a> as you might be getting either a<br><br>&#8211; shallow copy or <br>&#8211; a deep copy<br><br>What is the difference!?<a href=\"https:\/\/twitter.com\/TonyGidraph?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">@TonyGidraph<\/a> explains these concepts and shares some tips on how to generate deep copies.<a href=\"https:\/\/t.co\/YJoW9uaJbe\">https:\/\/t.co\/YJoW9uaJbe<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1569538146932752387?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">September 13, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>If you have been programming in Javascript for some time now, you have likely worked with copies even if you might not have realized it. The concept of copying might not seem important until you change a value in the &#8216;copy object&#8217; and expect the &#8216;original object&#8217; to remain the same. To effectively work with &#8230; <a title=\"Difference Between Shallow Copy and Deep Copy in JavaScript\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-shallow-vs-deep-copy\/\" aria-label=\"More on Difference Between Shallow Copy and Deep Copy in JavaScript\">Read more<\/a><\/p>\n","protected":false},"author":8,"featured_media":4258,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-4182","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4182","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=4182"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4182\/revisions"}],"predecessor-version":[{"id":4261,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4182\/revisions\/4261"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/4258"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=4182"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=4182"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=4182"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}