Great! Let’s now understand the difference between Shallow Copy and Deep Copy — an important concept in JavaScript when dealing with objects and arrays.
I’ll explain in English and Bangla, with examples.
🔁 Shallow Copy vs Deep Copy
Copy Type | Meaning (English) | ব্যাখ্যা (বাংলা) |
---|---|---|
Shallow Copy | Copies only the first level of the object/array. Nested objects are still referenced. | শুধুমাত্র উপরের স্তরের ডেটা কপি করে। ভিতরের (nested) অবজেক্ট বা অ্যারে একই রেফারেন্স থাকে। |
Deep Copy | Copies all levels, including nested objects. No references to the original. | সব স্তরের (nested সহ) ডেটা সম্পূর্ণ নতুন কপি হয়। মূল অবজেক্টের সঙ্গে আর কোনো সম্পর্ক থাকে না। |
🧪 Shallow Copy Example
const original = {
name: "Ali",
address: {
city: "Dhaka",
},
};
const shallowCopy = { ...original }; // Spread = shallow copy
shallowCopy.address.city = "Chittagong";
console.log(original.address.city); // Output: "Chittagong" ❌ (unexpected)
📌 Explanation:
Even though we copied original
into shallowCopy
, changing address.city
in shallowCopy
also affected the original, because nested objects are still linked (same reference).
📗 বাংলা: Shallow copy-তে address
অবজেক্টটি কপি হয়নি, শুধু রেফারেন্স গেছে। তাই যেকোনো পরিবর্তন মূল অবজেক্টেও প্রভাব ফেলে।
🔁 Deep Copy Example
const original = {
name: "Ali",
address: {
city: "Dhaka",
},
};
const deepCopy = JSON.parse(JSON.stringify(original)); // Deep copy
deepCopy.address.city = "Chittagong";
console.log(original.address.city); // Output: "Dhaka" ✅ (original unchanged)
📌 Explanation:
We used JSON.stringify()
+ JSON.parse()
to create a deep copy — now changing deepCopy
doesn’t affect the original.
📗 বাংলা: Deep copy-তে ভিতরের সব স্তরের ডেটা নতুনভাবে তৈরি হয়। তাই deepCopy
পরিবর্তন করলে original
অপরিবর্তিত থাকে।
🧠 Summary Table:
Feature | Shallow Copy | Deep Copy |
---|---|---|
🔄 Nested Object | Reference shared | Fully copied |
💥 Changes affect original? | ✅ Yes (for nested) | ❌ No |
🛠 Methods | Object.assign() , Spread ... |
JSON.parse(JSON.stringify()) , lodash cloneDeep() |
⚠️ Limitation | Not safe for deeply nested or complex types | Can be slower, but safer |
✅ When to Use Which?
Situation | Copy Type |
---|---|
Object has only primitive values (no nesting) | ✅ Shallow Copy |
Object has nested structure and needs full separation | ✅ Deep Copy |