Shallow vs Deep Copy in JavaScript

😅 I once changed a value in a “copied” object…... and somehow the original data changed too 💥 👉 That’s when I realized… I didn’t understand shallow vs deep copy properly. 🚀 Let’s break it down (this will save you from real bugs) 🧠 Why this matters In JavaScript, objects & arrays are reference types So copying them incorrectly = you might accidentally modify the original data 😬 📦 1. Shallow Copy A shallow copy only copies top-level values 👉 Nested objects are still shared (same reference) So: - Changing top-level → ✅ safe - Changing nested → 💥 affects original too ⚠️ The common mistake You think you created a new object… but deep inside, it’s still pointing to the same memory 😵 🔁 How to create shallow copy • Spread → {...obj} • Object.assign • Array methods → slice, Array.from 🔐 2. Deep Copy A deep copy creates a fully independent clone 👉 Every level is copied 👉 No shared references So: - Changing nested data → ✅ completely safe 🔁 How to create deep copy 👉 structuredClone() (Recommended) - Handles most data types - Modern & reliable 👉 JSON.parse(JSON.stringify()) - Quick but limited - loses functions, Dates, undefined 💡 Real Dev Insight Shallow copy is fast ⚡ Deep copy is safe 🛡️ 👉 Use shallow → for simple data 👉 Use deep → for nested structures 🚀 Final Thought: Most bugs don’t come from logic… 👉 They come from unexpected mutations Understand copying → write safer code 💪 #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #ShallowCopy #DeepCopy #LearnJavaScript #BuildInPublic #100DaysOfCode #LearnInPublic

  • code eg. for shallow and deep copy.

To view or add a comment, sign in

Explore content categories