🚀 Deep Clone an Object in JavaScript (without using JSON methods!) Ever tried cloning an object with const clone = JSON.parse(JSON.stringify(obj)); and realized it breaks when you have functions, Dates, Maps, or undefined values? 😬 Let’s learn how to deep clone an object the right way - without relying on JSON methods. What’s the problem with JSON.parse(JSON.stringify())? t’s a quick trick, but it: ❌ Removes functions ❌ Converts Date objects to strings ❌ Skips undefined, Infinity, and NaN ❌ Fails for Map, Set, or circular references So, what’s the alternative? ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). structuredClone() handles Dates, Maps, Sets, and circular references like a champ! structuredClone() can successfully clone objects with circular references (where an object directly or indirectly references itself), preventing the TypeError: Converting circular structure to JSON that occurs with JSON.stringify(). ✅ Option 2: Write your own recursive deep clone For learning purposes or environments without structuredClone(). ⚡ Pro Tip: If you’re working with complex data structures (like nested Maps, Sets, or circular references), use: structuredClone() It’s native, fast, and safe. Final Thoughts Deep cloning is one of those "simple but tricky" JavaScript topics. Knowing when and how to do it properly will save you hours of debugging in real-world projects. 🔥 If you found this helpful, 👉 Follow me for more JavaScript deep dives - made simple for developers. Let’s grow together 🚀 #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #AkshayPai #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
structuredClone is quite useful for such purposes. I guess in interviews, a recursive approach would be useful in case interviewer specifically tells us not to use built in methods and JSON methods.
Spot on! `structuredClone()` is undeniably the most robust and performant solution for deep cloning in modern JavaScript, gracefully handling complex types and circular references. Thanks for shedding light on these crucial distinctions!