Shallow vs Deep Copy in JavaScript

Here’s something commonly asked in JavaScript interviews 👇 Shallow vs Deep Copy Shallow Copy Copies only top-level properties. Nested objects are copied by reference, so changes affect the original. 👉 Ways: Object.assign(), spread (...), Array.from() Deep Copy Creates a fully independent copy, including nested objects. A common approach: JSON.parse(JSON.stringify(obj)) ⚠️ Catch with JSON.stringify() It fails for: • functions (removed) • undefined (removed or become null if arr) • Date (becomes string) • NaN / Infinity (become null) • Map, Set, RegExp (structure lost) • circular references (error) ✅ Better approach const newObj = structuredClone(obj) ✔ Handles most cases (Map, Set, Date, circular refs) ❌ Still can’t clone functions 🔥 Advanced: Custom Deep Clone If you also want to handle functions, you need a custom solution: function deepClone(obj) { if (obj === null || typeof obj !== "object") return obj; if (obj instanceof Date) return new Date(obj); if (obj instanceof RegExp) return new RegExp(obj); if (typeof obj === "function") return obj.bind({}); if (Array.isArray(obj)) { return obj.map(item => deepClone(item)); } const cloned = {}; for (let key in obj) { cloned[key] = deepClone(obj[key]); } return cloned; } ⚠️ Note: • Functions are copied by reference (true cloning isn’t really possible) 💡 Takeaway • Use shallow copy for simple cases • Use structuredClone() for most real scenarios • Use custom clone only when you need full control Don't forget to follow Mohit Sharma 🚀 for more. #JavaScript #Frontend #WebDevelopment #InterviewPrep #ReactJS

To view or add a comment, sign in

Explore content categories