JavaScript Shallow Copy Gotcha: How to Deep Clone

😩 I changed one object... and everything else broke. Classic JavaScript moment. You think you’ve copied an object — but you’ve only cloned the surface. Here’s what happened to me recently 👇 const user = { name: "John", address: { city: "Berlin" } }; const clone = { ...user }; clone.address.city = "Paris"; console.log(user.address.city); // 😱 "Paris" Wait — what?! I just wanted a copy… not to move the entire family. 🧠 What’s going on? The spread operator { ...obj } or Object.assign() only makes a shallow copy. That means nested objects or arrays still share references with the original. So when you mutate one, the other changes too. ✅ The Fix If you need a deep copy, you have a few safe options: // 1️⃣ Simple & built-in (modern JS) const deepClone = structuredClone(user); // 2️⃣ Old-school workaround const deepClone = JSON.parse(JSON.stringify(user)); // 3️⃣ For complex cases (like Dates, Maps, etc.) import _ from "lodash"; const deepClone = _.cloneDeep(user); Now user and deepClone are fully independent. 💡 Takeaway > A shallow copy copies values. A deep copy copies the entire structure. Know which one you need — or your state bugs will come back to haunt you. 👻 🗣️ Your Turn Have you ever been burned by this shallow copy issue? What’s your go-to method for safe cloning? #JavaScript #WebDevelopment #CodingTips #FrontendDevelopment #CleanCode #ProgrammingBugs #ES6 #CodeSmarter #DevCommunity

  • graphical user interface, text

lodash library can be heavy only for cloneDeep. Try punyutility. Light weight library comes with cloneDeep.

Like
Reply

To view or add a comment, sign in

Explore content categories