π Deep Copy vs Shallow Copy in JavaScript: Explained for Beginners


When working with JavaScript, especially with objects and arrays, youβll often need to copy data. However, not all copies behave the same. This brings us to two key concepts:
Shallow Copy
Deep Copy
Understanding the difference can save you from frustrating bugs and unexpected behavior in your code β especially when working with nested data structures or building apps with frameworks like React.
π Whatβs the Difference?
Aspect | Shallow Copy | Deep Copy |
Definition | Creates a new object/array, but references for nested objects are still shared with the original. | Creates a brand-new object/array including deeply nested values. No shared references. |
Effect on Modification | Changes to nested objects in the copy affect the original. | Changes in the copy do not affect the original. |
Use case | Good for flat structures or when you want to keep shared references. | Ideal when you need a fully independent clone. |
π§ How to Make a Copy in JavaScript
π¦ Copying Objects
π§ͺ Example: Shallow Copy Using Object.assign()
javascriptCopyEditconst original = { name: "Alice", address: { city: "Paris" } };
const copy = Object.assign({}, original);
copy.address.city = "London";
console.log(original.address.city); // β "London" β the original is affected
π§ͺ Using the Spread Operator (...
)
javascriptCopyEditconst original = { name: "Bob", address: { city: "Rome" } };
const copy = { ...original };
copy.address.city = "Berlin";
console.log(original.address.city); // β "Berlin" β still shallow!
π Real-world scenario: Imagine copying a user profile to modify the copy. If it has nested data (like address), and you use a shallow copy, changes might unintentionally affect the original user profile. Not good!
π Copying Arrays
π§ͺ Shallow Copy Using .slice()
javascriptCopyEditconst original = [[1, 2], [3, 4]];
const copy = original.slice();
copy[0][0] = 99;
console.log(original[0][0]); // β 99 β original changed!
π§ͺ Using Spread for Arrays
javascriptCopyEditconst original = [[10, 20], [30, 40]];
const copy = [...original];
copy[1][1] = 999;
console.log(original[1][1]); // β 999 β still shallow!
π§ Deep Copy Techniques
β
1. Using JSON.stringify()
+ JSON.parse()
javascriptCopyEditconst original = { name: "Zoe", hobbies: ["reading", "biking"] };
const copy = JSON.parse(JSON.stringify(original));
copy.hobbies[0] = "gaming";
console.log(original.hobbies[0]); // β
"reading" β deep copy works!
β οΈ Limitations:
- Doesnβt work with functions,
undefined
,Date
, or special object types likeMap
,Set
.
β 2. Using Libraries Like Lodash
Lodashβs cloneDeep
is very reliable.
javascriptCopyEditimport cloneDeep from 'lodash/cloneDeep';
const original = { user: { name: "Tom", settings: { theme: "dark" } } };
const copy = cloneDeep(original);
copy.user.settings.theme = "light";
console.log(original.user.settings.theme); // β
"dark" β completely independent!
π©βπ« Real World Use Case: React State Management
In React, state updates should never mutate the original state directly. If you accidentally create a shallow copy of a deeply nested state object and update it, your UI might not re-render properly, or you might introduce hard-to-find bugs.
β Best Practice Example
javascriptCopyEditconst updatedUsers = users.map(user => ({
...user,
profile: { ...user.profile, age: user.profile.age + 1 }
}));
This ensures immutability β a key principle in modern JavaScript development.
π§ Best Practices
Understand your data: If it has nesting, shallow copying will not be enough.
Use deep copy when needed: Especially when working with forms, state, or any structure passed to components or reused elsewhere.
Immutable patterns: Use immutability libraries or patterns to ensure safer code.
Debug carefully: If you see strange behavior, double-check if youβre mutating shared references.
π§΅ Conclusion
Copying isnβt always as simple as it looks in JavaScript. Knowing when to use a shallow or deep copy can save you from unexpected side effects β especially as your apps grow more complex.
Want to practice? Try copying an array of objects and modifying just one entry without affecting the rest. Or clone a nested object and test whether the original stays intact!
If you have questions or want more examples, feel free to ask. π
Would you like a downloadable version of this article or maybe a code playground example too?
leave a comment βcodeβ
Subscribe to my newsletter
Read articles from Zia Ur Rehman directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Zia Ur Rehman
Zia Ur Rehman
π§ Are you facing challenges like slow website performance, poor user experience, cross-browser issues, and difficulty integrating with back-end systems, all while trying to manage business growth without a streamlined digital solution? π€ Are you struggling to reach a wider audience, improve customer engagement, and stay competitive without a web app, while dealing with inefficient operations, limited scalability, and missed revenue opportunities? π Build a web app to expand reach, improve engagement, and streamline operations for growth. βοΈ Optimize performance, enhance user experience, and integrate systems with a smooth, scalable solution. π¨βπ» I am Zia-Ur-Rehman a MERN Developer with experience in building scalable and high-performing web applications that solve buisness Problems. I worked with the startup to Help their clients by developing highly scalable webApps to make their global buisness mangable with one click across globe. β Frontend Development to create responsive, user-friendly interfaces that solve the problems of your audience. β Figma to Next.js Functional App transforming your designs into interactive, high-performance Web apps. β Web App Development to expand your reach and improve customer engagement.β Performance Optimization for faster load times and seamless user experience.β Cross-Browser Compatibility ensuring your app works perfectly everywhere.β Backend Integration to streamline operations and boost business efficiency.If you have an idea that will capture market share, why are you waiting? π DM me today or email me (emailtozia0@gmail.com) and get started!