{"id":6476,"date":"2025-06-07T01:32:27","date_gmt":"2025-06-07T01:32:27","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6476"},"modified":"2025-06-07T01:32:27","modified_gmt":"2025-06-07T01:32:27","slug":"shallow-vs-deep-copy-in-javascript-2","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/shallow-vs-deep-copy-in-javascript-2\/","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, it&#8217;s crucial to understand how data is copied and referenced. Two common concepts that developers frequently encounter are &#8220;shallow copy&#8221; and &#8220;deep copy.&#8221; This article will clarify the differences between the two, exploring the implications of copying strategies in JavaScript programming.<\/p>\n<h2>What is a Copy in JavaScript?<\/h2>\n<p>In JavaScript, copying refers to creating a duplicate of a value, whether it&#8217;s a primitive type or an object. Primitive types (such as strings, numbers, and booleans) are copied by value, whereas objects (which include arrays and functions) are copied by reference. Understanding this distinction is essential for working effectively with data structures in JavaScript.<\/p>\n<h2>Shallow Copy Explained<\/h2>\n<p>A shallow copy creates a new object that is a copy of the original object, but it only copies values at the first level. If the original object contains references to other objects, the shallow copy will not create copies of those nested objects; instead, it will reference them. This means that changes to the nested objects will be reflected in both the original and the copied object.<\/p>\n<h3>Creating a Shallow Copy<\/h3>\n<p>There are several ways to create a shallow copy in JavaScript:<\/p>\n<h4>1. Using Object.assign()<\/h4>\n<pre><code>const originalObject = { a: 1, b: { c: 2 } };\nconst shallowCopy = Object.assign({}, originalObject);\n\nshallowCopy.a = 3;          \/\/ Change on shallow copy\nshallowCopy.b.c = 5;       \/\/ Change on nested object\n\nconsole.log(originalObject); \/\/ { a: 1, b: { c: 5 } }\nconsole.log(shallowCopy);    \/\/ { a: 3, b: { c: 5 } }\n<\/code><\/pre>\n<h4>2. Using the Spread Operator<\/h4>\n<pre><code>const originalArray = [1, 2, { a: 3 }];\nconst shallowCopyArray = [...originalArray];\n\nshallowCopyArray[0] = 99;          \/\/ Change on shallow copy\nshallowCopyArray[2].a = 100;       \/\/ Change on nested object\n\nconsole.log(originalArray); \/\/ [1, 2, { a: 100 }]\nconsole.log(shallowCopyArray); \/\/ [99, 2, { a: 100 }]\n<\/code><\/pre>\n<h2>Deep Copy Explained<\/h2>\n<p>A deep copy creates a new object and recursively copies all objects and nested structures within the original object. This means that changes made to nested objects in the deep copy will not affect the original object, as they are entirely distinct entities.<\/p>\n<h3>Creating a Deep Copy<\/h3>\n<p>Deep copying can be achieved through various methods, including:<\/p>\n<h4>1. JSON Methods<\/h4>\n<p>The simplest way to create a deep copy, especially for plain objects, is to use JSON methods, such as <code>JSON.stringify()<\/code> followed by <code>JSON.parse()<\/code>.<\/p>\n<pre><code>const originalObject = { a: 1, b: { c: 2 } };\nconst deepCopy = JSON.parse(JSON.stringify(originalObject));\n\ndeepCopy.b.c = 5;          \/\/ Change on deep copy\n\nconsole.log(originalObject); \/\/ { a: 1, b: { c: 2 } }\nconsole.log(deepCopy);       \/\/ { a: 1, b: { c: 5 } }\n<\/code><\/pre>\n<h4>2. Using a Custom Deep Copy Function<\/h4>\n<p>For more complex scenarios, especially when dealing with non-JSON-compatible objects (like functions or dates), you may require a custom deep cloning function.<\/p>\n<pre><code>function deepCopy(obj) {\n    if (obj === null || typeof obj !== 'object') {\n        return obj;\n    }\n\n    if (Array.isArray(obj)) {\n        return obj.map(item =&gt; deepCopy(item));\n    }\n\n    const copy = {};\n    for (let key in obj) {\n        if (obj.hasOwnProperty(key)) {\n            copy[key] = deepCopy(obj[key]);\n        }\n    }\n    return copy;\n}\n\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = deepCopy(originalObject);\n\ndeepCopyObject.b.c = 5; \/\/ Change on deep copy\n\nconsole.log(originalObject); \/\/ { a: 1, b: { c: 2 } }\nconsole.log(deepCopyObject); \/\/ { a: 1, b: { c: 5 } }\n<\/code><\/pre>\n<h2>Key Differences Between Shallow and Deep Copy<\/h2>\n<table>\n<thead>\n<tr>\n<th>Aspect<\/th>\n<th>Shallow Copy<\/th>\n<th>Deep Copy<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Definition<\/td>\n<td>Only copies the top-level properties of an object.<\/td>\n<td>Recursively copies all nested properties of an object.<\/td>\n<\/tr>\n<tr>\n<td>Nested Objects<\/td>\n<td>References nested objects.<\/td>\n<td>Creates new instances of nested objects.<\/td>\n<\/tr>\n<tr>\n<td>Performance<\/td>\n<td>Generally faster due to fewer objects being copied.<\/td>\n<td>Generally slower due to recursion and object creation.<\/td>\n<\/tr>\n<tr>\n<td>Use Case<\/td>\n<td>When you only need a copy of the top-level properties.<\/td>\n<td>When you want to avoid side effects from nested object changes.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Common Pitfalls<\/h2>\n<p>When working with shallow and deep copies, there are some common pitfalls to avoid:<\/p>\n<ul>\n<li><strong>Accidental Mutation:<\/strong> With shallow copies, you may unintentionally modify the original object when altering nested properties. Be aware of where your changes are happening.<\/li>\n<li><strong>Performance Considerations:<\/strong> Deep copying can be resource-intensive, especially for large data structures. Use it judiciously, and prefer shallow copies when possible.<\/li>\n<li><strong>JSON Deep Copy Limitations:<\/strong> The <code>JSON.stringify()<\/code> and <code>JSON.parse()<\/code> method won\u2019t work on objects containing functions, undefined, symbol, or non-serializable data types (like Dates or RegExps).<\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>Understanding the differences between shallow and deep copies is essential for JavaScript developers. Both methods have their own use cases based on the requirements of your application. While shallow copies are efficient and useful for simple structures, deep copies provide a robust solution for complex objects. By mastering how to manipulate and copy objects effectively, you can enhance the performance and reliability of your JavaScript applications.<\/p>\n<p>Whether you\u2019re building front-end interfaces or back-end services, mastering these concepts will help you handle data with confidence and minimize unwanted side effects.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understanding Shallow vs Deep Copy in JavaScript When working with objects and arrays in JavaScript, it&#8217;s crucial to understand how data is copied and referenced. Two common concepts that developers frequently encounter are &#8220;shallow copy&#8221; and &#8220;deep copy.&#8221; This article will clarify the differences between the two, exploring the implications of copying strategies in JavaScript<\/p>\n","protected":false},"author":100,"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":{"0":"post-6476","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-javascript","7":"tag-javascript"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6476","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\/100"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6476"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6476\/revisions"}],"predecessor-version":[{"id":6477,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6476\/revisions\/6477"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6476"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6476"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6476"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}