What is the difference between shallow copy and deep copy in JavaScript?
Asked on Aug 07, 2024
Answer
In JavaScript, a shallow copy duplicates the top-level properties of an object, while a deep copy duplicates all nested objects, creating independent copies. Here's how you can create each type of copy:
<!-- BEGIN COPY / PASTE -->
// Shallow copy using Object.assign
const original = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, original);
// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- A shallow copy (using Object.assign) copies only the top-level properties. Changes to nested objects in the original will affect the shallow copy.
- A deep copy (using JSON methods) creates a completely independent copy, but it only works for JSON-safe objects (e.g., no functions, undefined, or symbols).
- For complex objects, consider using libraries like Lodash for deep cloning.
- Always choose the appropriate method based on your data structure and requirements.
Recommended Links:
← Back to All Questions