Avoiding the Pitfall of Shallow Copy in JavaScript

💡 Ever changed a copy of an object… and accidentally changed the original too? If you’ve worked with JavaScript, you know this painful trap all too well! Let’s clarify the difference between shallow copy and deep copy, and see how modern JS handles it. 🔹 Shallow Copy A shallow copy duplicates only the top-level properties. Nested objects or arrays are still shared. const original = { name: "Alice", details: { age: 25 } }; const shallowCopy = { ...original }; shallowCopy.details.age = 30; console.log(original.details.age); // 30 → original object changed! ✅ Top-level copied. ⚠️ Nested objects still reference the same memory. 🔹 Deep Copy A deep copy duplicates everything, including nested objects, so changes don’t affect the original. 1️⃣ Using JSON.stringify() + JSON.parse() const original = { name: "Alice", details: { age: 25 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ⚠️ Limitation: Doesn’t handle Dates, Maps, Sets, functions, or circular references. 2️⃣ Using structuredClone() (Modern JS) const original = { name: "Alice", details: { age: 25 } }; const deepCopy = structuredClone(original); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ✅ Handles most types, including Date, Map, Set, etc. ⚠️ Available in modern browsers & Node.js v17+. #JS #JavaScript #WebDevelopment #DeepCopy #ShallowCopy #CodingTips #Programming

To view or add a comment, sign in

Explore content categories