JavaScript Interview Question: Shallow vs Deep Copy

Day 48/50 – JavaScript Interview Question? Question: What is the difference between shallow copy and deep copy? How do you implement each? Simple Answer: Shallow copy duplicates top-level structure but keeps references to nested objects. Deep copy recursively duplicates all nested objects. Shallow: spread operator, Object.assign(). Deep: structuredClone(), JSON.parse(JSON.stringify()), or custom recursion. 🧠 Why it matters in real projects: Wrong copy method causes bugs in state management (React/Redux), data manipulation, and form handling. Shallow copies are fast but dangerous with nested data. Deep copies prevent mutations but can be expensive. 💡 One common mistake: Using spread operator for nested objects expecting deep copy. Mutations affect the original! Also using JSON.parse(JSON.stringify()) which fails for functions, dates, undefined, and circular references. 📌 Bonus: const original = { name: 'Alice', address: { city: 'NYC' }, hobbies: ['reading'] }; // Shallow copy - nested objects still shared const shallow = { ...original }; shallow.address.city = 'LA'; console.log(original.address.city); // 'LA' - Oops! // Deep copy - Modern way (best!) const deep = structuredClone(original); deep.address.city = 'Boston'; console.log(original.address.city); // 'NYC' - ✓ Independent! // JSON method (has limitations) const deep2 = JSON.parse(JSON.stringify(original)); // ✗ Loses functions const obj = { fn: () => {} }; JSON.parse(JSON.stringify(obj)); // {} - lost! // ✗ Breaks dates const obj2 = { date: new Date() }; JSON.parse(JSON.stringify(obj2)); // date becomes string! // Custom deep clone (interview favorite) function deepClone(obj, hash = new WeakMap()) { if (obj === null || typeof obj !== 'object') return obj; if (hash.has(obj)) return hash.get(obj); // Circular ref if (obj instanceof Date) return new Date(obj); if (Array.isArray(obj)) { const arr = []; hash.set(obj, arr); obj.forEach((item, i) => arr[i] = deepClone(item, hash)); return arr; } const copy = {}; hash.set(obj, copy); Object.keys(obj).forEach(key => { copy[key] = deepClone(obj[key], hash); }); return copy; } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories