{"id":8435,"date":"2025-07-30T11:32:31","date_gmt":"2025-07-30T11:32:31","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=8435"},"modified":"2025-07-30T11:32:31","modified_gmt":"2025-07-30T11:32:31","slug":"shallow-vs-deep-copy-in-javascript-4","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/shallow-vs-deep-copy-in-javascript-4\/","title":{"rendered":"Shallow vs Deep Copy in JavaScript"},"content":{"rendered":"<h1>Understanding Shallow vs Deep Copy in JavaScript<\/h1>\n<p>When working with objects and arrays in JavaScript, developers often encounter the need to create copies of these data structures. However, not all copies are created equal. In this article, we will explore the differences between shallow and deep copies, their implications, and how to properly implement each method in JavaScript. This understanding is crucial for preventing unintended side effects in your applications.<\/p>\n<h2>What is a Copy?<\/h2>\n<p>A copy is simply a duplicate of a data structure, such as an object or an array. In JavaScript, copying is essential when you want to preserve the original object while manipulating a new one. However, the way in which the copy is made can lead to different results\u2014this is where shallow and deep copying come into play.<\/p>\n<h2>Shallow Copy Explained<\/h2>\n<p>A <strong>shallow copy<\/strong> of an object creates a new object that is a copy of the original object but only copies the references of nested objects, not their actual values. This means that if the original object contains other objects or arrays, the copied object will still reference these nested structures rather than creating copies of them.<\/p>\n<h3>How to Create a Shallow Copy<\/h3>\n<p>There are several ways to create a shallow copy in JavaScript:<\/p>\n<ul>\n<li><strong>Object Spread Operator<\/strong> (<code>{...obj}<\/code>)<\/li>\n<li><strong>Array Spread Operator<\/strong> (<code>[...arr]<\/code>)<\/li>\n<li><strong>Object.assign()<\/strong><\/li>\n<\/ul>\n<h4>Examples of Shallow Copy<\/h4>\n<p>Let\u2019s look at some examples:<\/p>\n<h5>1. Using Object Spread Operator<\/h5>\n<pre><code>const original = { a: 1, b: { c: 2 } };<br>\nconst shallowCopy = {...original};<br>\nshallowCopy.a = 3;<br>\nshallowCopy.b.c = 4;<br>\nconsole.log(original);  \/\/ Output: { a: 1, b: { c: 4 } }\nconsole.log(shallowCopy); \/\/ Output: { a: 3, b: { c: 4 } }<\/code>\n<\/pre>\n<h5>2. Using Object.assign()<\/h5>\n<pre><code>const original = { x: 10, y: { z: 20 } };<br>\nconst shallowCopy = Object.assign({}, original);<br>\nshallowCopy.x = 30;<br>\nshallowCopy.y.z = 40;<br>\nconsole.log(original);  \/\/ Output: { x: 10, y: { z: 40 } }\nconsole.log(shallowCopy); \/\/ Output: { x: 30, y: { z: 40 } }<\/code>\n<\/pre>\n<p>As shown in the examples above, changes to the nested object <code>b<\/code> or <code>y<\/code> in the shallow copy affect the original object as well since both point to the same reference.<\/p>\n<h2>Deep Copy Explained<\/h2>\n<p>A <strong>deep copy<\/strong>, on the other hand, creates a new object and recursively copies every property from the original object, including the nested objects. Thus, the result is a complete clone with no shared references.<\/p>\n<h3>How to Create a Deep Copy<\/h3>\n<p>Deep copying can be achieved using the following methods:<\/p>\n<ul>\n<li><strong>JSON.parse(JSON.stringify())<\/strong><\/li>\n<li><strong>Recursive function<\/strong><\/li>\n<li><strong>Libraries such as Lodash<\/strong><\/li>\n<\/ul>\n<h4>Examples of Deep Copy<\/h4>\n<p>Let\u2019s dive into some examples of creating deep copies:<\/p>\n<h5>1. Using JSON methods<\/h5>\n<pre><code>const original = { a: 1, b: { c: 2 } };<br>\nconst deepCopy = JSON.parse(JSON.stringify(original));<br>\ndeepCopy.a = 3;<br>\ndeepCopy.b.c = 4;<br>\nconsole.log(original);  \/\/ Output: { a: 1, b: { c: 2 } }\nconsole.log(deepCopy);  \/\/ Output: { a: 3, b: { c: 4 } }<\/code>\n<\/pre>\n<h5>2. Using a Recursive Function<\/h5>\n<pre><code>function deepCopy(obj) {<br>\n    if (obj === null || typeof obj !== 'object') return obj;<br>\n    const copy = Array.isArray(obj) ? [] : {}; <br>\n    for (const key in obj) {<br>\n        copy[key] = deepCopy(obj[key]);<br>\n    }<br>\n    return copy;<br>\n}<br>\nconst original = { x: 10, y: { z: 20 } };<br>\nconst deepCopy = deepCopy(original);<br>\ndeepCopy.x = 30;<br>\ndeepCopy.y.z = 40;<br>\nconsole.log(original);  \/\/ Output: { x: 10, y: { z: 20 } }\nconsole.log(deepCopy);  \/\/ Output: { x: 30, y: { z: 40 } }<\/code>\n<\/pre>\n<h2>When to Use Shallow vs. Deep Copy<\/h2>\n<p>The choice between using a shallow or deep copy depends on your use case:<\/p>\n<ul>\n<li><strong>Use Shallow Copy:<\/strong> When you are sure that your object does not contain nested objects that need to be independently modified.<\/li>\n<li><strong>Use Deep Copy:<\/strong> When your object contains nested structures, and you need a completely independent duplicate.<\/li>\n<\/ul>\n<h2>Common Pitfalls<\/h2>\n<p>It&#8217;s crucial to understand the differences between shallow and deep copies because mistakenly using one when the other is required can introduce bugs and unexpected behavior. Here are some common pitfalls:<\/p>\n<ul>\n<li>Modifying a deep-nested structure in a shallow-copied object can inadvertently affect the original object.<\/li>\n<li>Using JSON methods for deep copying has limitations\u2014functions, <code>undefined<\/code>, and non-serializable objects (like <code>Date<\/code> or <code>Map<\/code>) will be lost.<\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>The decision between shallow and deep copies is a foundational concept in JavaScript programming that affects how data structures are manipulated. By understanding the nature of these copies, you can write more predictable and error-free code. Remember to consider your application&#8217;s requirements and use the appropriate copying method based on the context.<\/p>\n<p>Stay informed and practice these concepts as they are pivotal to mastering JavaScript object manipulation!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understanding Shallow vs Deep Copy in JavaScript When working with objects and arrays in JavaScript, developers often encounter the need to create copies of these data structures. However, not all copies are created equal. In this article, we will explore the differences between shallow and deep copies, their implications, and how to properly implement each<\/p>\n","protected":false},"author":78,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[172],"tags":[330],"class_list":["post-8435","post","type-post","status-publish","format-standard","category-javascript","tag-javascript"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8435","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/78"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=8435"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8435\/revisions"}],"predecessor-version":[{"id":8436,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8435\/revisions\/8436"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=8435"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=8435"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=8435"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}