Home >Web Front-end >JS Tutorial >Shallow Copy vs. Deep Copy in JavaScript
In JavaScript, copying objects or arrays can be categorized into shallow copy and deep copy. Understanding the difference is critical when dealing with complex data structures, especially those containing nested objects or arrays.
This guide explains these concepts, their characteristics, methods to implement them, and when to use each.
Definition
A shallow copy creates a duplicate of the top-level properties of an object or array. However, for nested objects or arrays, only the references are copied, not the actual data.
Characteristics
1.1 Using Object.assign()
const original = { a: 1, b: { c: 2 } }; const shallowCopy = Object.assign({}, original); shallowCopy.b.c = 42; console.log(original.b.c); // OUTPUT: 42 (The original object also affected due to shared reference)
1.2 Using the Spread Operator (...)
const original = { a: 1, b: { c: 2 } }; const shallowCopy = { ...original }; shallowCopy.b.c = 90; console.log(original.b.c); // OUTPUT: 90
1.3 Lets see an example of shallow copy on Array Methods (slice, concat)
const original = [1, 2, [3, 4]]; const shallowCopy = original.slice(); shallowCopy[2][0] = 10; console.log(original[2][0]); // OUTPUT: 10
Definition
A deep copy creates a fully independent duplicate of an object or array. All levels, including nested structures, are recursively copied. Changes to the copied structure do not affect the original, and vice versa.
Characteristics
2.1 Using JSON.stringify() and JSON.parse()
const original = { a: 1, b: { c: 2 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.b.c = 42; console.log(original.b.c); // OUTPUT: 2 (original remains unaffected)
2.2 Using structuredClone()
A modern method for deep copying that supports circular references and special objects like Date.
const original = { a: 1, b: { c: 2 }, date: new Date() }; const deepCopy = structuredClone(original); deepCopy.b.c = 42; console.log(original.b.c); // OUTPUT: 2 console.log(original.date === deepCopy.date); // FALSE
2.3 Using a Custom Recursive Function
A flexible solution for handling complex cases manually.
function deepCopy(obj) { if (obj === null || typeof obj !== "object") return obj; if (Array.isArray(obj)) return obj.map(deepCopy); const copy = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = deepCopy(obj[key]); } } return copy; } const original = { a: 1, b: { c: 2 } }; const deepCopyObj = deepCopy(original); deepCopyObj.b.c = 42; console.log(original.b.c); // OUTPUT: 2
Shallow Copy
Deep Copy
Shallow Copy
Deep Copy
This is an in depth explanation of the Shallow copy and Deep copy of objects in the JavaScript. Choose the appropriate method based on your use case and performance requirements.
The above is the detailed content of Shallow Copy vs. Deep Copy in JavaScript. For more information, please follow other related articles on the PHP Chinese website!