JavaScript Shallow vs Deep Copy: Understanding the Difference

💡 JavaScript Shallow Copy vs Deep Copy 1. Shallow Copy: 📌 Copies only top-level properties (primitives). 📌 Nested objects (arrays, objects) share the same reference. 🎙️ Modifying a top-level primitive in the copy does not affect the original, but modifying a nested object will affect the original, because both share the same reference. 💡 Example: const original= { a: 1, b: { c: 2 } }; const copy= { ...original }; copy.a =100; copy.b.c =200; console.log(original.a); // 1 top-level primitive unaffected console.log(original.b.c); // 200 nested object changed 2. Deep Copy: 📌 Creates a completely independent copy of the object, including all nested objects or arrays. 📌 Modifying any part of the deep copy, including deeply nested properties, has no affect on the original object ⚙️ Methods: Simple objects: JSON.parse(JSON.stringify(obj)) Complex objects: structuredClone(obj) or lodash.cloneDeep(obj) 💡 Example: const original = {  name: "Vijay",  hobbies: ["Acting", "Dancing"],  address: { city: "Ramnad", country: "India" } }; const copy = structuredClone(original); copy.name = "Ajith"; copy.hobbies.push("Racing"); copy.address.city = "Chennai"; console.log(original); /* {  name: "Vijay",  hobbies: ["Acting", "Dancing"],  address: { city: "Ramnad", country: "India" } } */ console.log(copy); /* {  name: "Ajith",  hobbies: ["Acting", "Dancing", "Racing"],  address: { city: "Chennai", country: "India" } } */ #JavaScript #Coding #Programming #TechPost #ShallowCopy #DeepCopy

To view or add a comment, sign in

Explore content categories