JavaScript Interview Question: Shallow vs Deep Copy

🚨 𝗧𝗵𝗲 𝗠𝗢𝗦𝗧 𝗖𝗼𝗺𝗺𝗼𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 🚨 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 𝘃𝘀 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 Ever changed one object… and another object updated too? 😵 Interviewers LOVE this bug — because most devs miss why it happens. 🧠 𝗧𝗵𝗲 𝗥𝗘𝗔𝗟 𝗥𝗲𝗮𝘀𝗼𝗻 𝗜𝘁 𝗖𝗵𝗮𝗻𝗴𝗲𝘀 👉 𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝘃𝘀 𝗡𝗼𝗻-𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝘃𝗮𝗹𝘂𝗲𝘀 ✅ 𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝘃𝗮𝗹𝘂𝗲𝘀 string, number, boolean, null, undefined Copied by value Each variable gets its own copy Safe from side effects ❌ 𝗡𝗼𝗻-𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝘃𝗮𝗹𝘂𝗲𝘀 object, array, function Copied by reference Multiple variables point to the same memory location This is where bugs begin 🐛 🧩 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 (𝗧𝗵𝗲 𝗧𝗿𝗮𝗽) A shallow copy copies: ✅ Primitive values → by value ❌ Nested objects → by reference const original = { name: "JS", skills: { lang: "JavaScript" } }; const copy = { ...original }; copy.skills.lang = "TypeScript"; console.log(original.skills.lang); // TypeScript 😬 📌 Why did it change? Because skills is a non-primitive, and both objects reference the same memory. 🧩 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 (𝗧𝗵𝗲 𝗦𝗮𝗳𝗲 𝗪𝗮𝘆) A deep copy duplicates all levels, including non-primitive values. const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.skills.lang = "Python"; console.log(original.skills.lang); // JavaScript ✅ Now each object lives in its own memory space. ⚡ Why Interviewers Love This Question ✔️ Tests memory understanding, not syntax ✔️ Reveals React state mutation mistakes ✔️ Common Redux / Context API bug ✔️ Asked in React, JS & System Design rounds 🧠 Interview Rule to Remember Primitive? → Safe copy Non-Primitive? → Reference alert 🚨 Nested state in React? → Deep copy ONLY Complex objects? → structuredClone() or lodash.cloneDeep() 💡 If you understand this, you’re already ahead of 70% of candidates. #JavaScript #ReactJS #FrontendInterview #WebDevelopment #SoftwareEngineering #CodingTips

To view or add a comment, sign in

Explore content categories