JavaScript Interview Question: Deep vs Shallow Copy

Day 12/50 – JavaScript Interview Question? Question: What is the difference between deep copy and shallow copy? Simple Answer: A shallow copy duplicates only the top-level properties, keeping references to nested objects. A deep copy recursively duplicates all levels, creating completely independent copies. 🧠 Why it matters in real projects: Understanding this prevents bugs when modifying copied objects. In React/Redux, shallow copies are often sufficient for state updates, but nested state requires deep copying. Financial data, user profiles, and configuration objects often need deep copies. 💡 One common mistake: Using spread operator {...obj} or Object.assign() and thinking you have a deep copy. These only perform shallow copies! 📌 Bonus: const original = { name: 'John', address: { city: 'NYC' } }; // Shallow copy - nested objects still shared const shallow = { ...original }; shallow.address.city = 'LA'; console.log(original.address.city); // "LA" - Oops! // Deep copy options: // 1. Modern way (careful with functions/dates) const deep1 = structuredClone(original); // 2. JSON method (loses functions, dates become strings) const deep2 = JSON.parse(JSON.stringify(original)); // 3. Use lodash for complex objects const deep3 = _.cloneDeep(original); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories