Shallow vs Deep Copy in JavaScript: A Complete Guide with Examples
Effectively managing primitive data structures in JavaScript is essential for developing stable, predictable applications. A common source…
Shallow vs Deep Copy in JavaScript: A Complete Guide with Examples
Effectively managing primitive data structures in JavaScript is essential for developing stable, predictable applications. A common source of subtle bugs — and a critical concept for robust code and state management — is understanding the difference between shallow copy and deep copy when working with objects and arrays.

When shopping, if we use two bags to carry the same set of items together, that’s like a shallow copy — both bags refer to the same items. But if we place identical items separately in each bag, that’s a deep copy — each bag has its own copy of the items. What is a Shallow Copy?
For those familiar with languages like C or C++, a shallow copy is similar to passing a variable by reference — changes affect the original data. On the other hand, a deep copy is like passing by value — a completely independent copy is made, so changes don’t affect the original.
What is a Shallow Copy?
A shallow copy creates a new object or array that contains the same top-level properties or elements as the original. However, if any of those properties are themselves objects or arrays, only their references are copied — not their actual content. This means that changes to nested structures in the copied object will also reflect in the original, since both share the same references for those nested values.
Example:
const original = { name: "John", details: { age: 30 } };
const shallowCopy = { ...original };
shallowCopy.details.age = 40;
console.log(original.details.age); // Output: 40
Mutations to nested properties of the copy are reflected in the original object because they both point to the same nested reference.
What is a Deep Copy?
A deep copy goes beyond surface-level properties, recursively duplicating all nested objects and arrays. This creates a completely independent copy, eliminating any shared references between the copied and original objects at all levels.
Example:
const original = { name: "John", details: { age: 30 } };
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.details.age = 40;
console.log(original.details.age); // Output: 30
Changes to any property, at any depth, in the copied object do not affect the original.
Key Differences: Shallow vs. Deep Copy

Methods for Copying Primitive datatypes
Including Examples
Shallow Copy Methods
Assignment Operator (=)
Example:
const original = { name: "Alice" };
const copy = original;
copy.name = "Bob";
// Both 'original' and 'copy' now have name: "Bob"
Spread Syntax ({ ...obj })
Example:
const original = { name: "Alice", details: { age: 25 } };
const shallowCopy = { ...original };
shallowCopy.details.age = 30;
// original.details.age is now 30 as well
**Object.assign()**
Example:
const original = { name: "Alice", info: { city: "NYC" } };
const shallowCopy = Object.assign({}, original);
shallowCopy.info.city = "LA";
// original.info.city is now "LA"
Array Methods (slice() and from())
Example with slice():
const numbers = [1, 2, [3, 4]];
const shallowArray = numbers.slice();
shallowArray[2][0] = 99;
// numbers[2][0] is also 99
Example with Array.from():
const original = [1, 2, 3];
const copy = Array.from(original);
copy[0] = 9;
// original[0] stays 1
Deep Copy Methods
**JSON.parse(JSON.stringify(obj))**
- Pros: Simple for plain objects and arrays.
- Cons: Loses
Date,undefined,Infinity, functions, instances of custom classes. Cannot process non-serializable objects (eg. functions) and circular references .
Example:
const original = { user: "Alice", details: { age: 25 } };
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.details.age = 30;
// original.details.age remains 25
**structuredClone(obj)**
- Pros: Handles
Date,Map,Set,RegExp,Error. Standardized API. - Cons: Not available in all JavaScript environments (e.g., Node.js < v17); does not preserve prototypes, functions, or getters/setters.
- Example:
const original = { name: "Alice", date: new Date() };
const deepCopy = structuredClone(original);
deepCopy.name = "Bob";
// original.name stays "Alice"JSON.parse(JSON.stringify(obj))
**lodash.cloneDeep(obj)**
- Pros: Handles edge cases, reliable for most scenarios.
- Cons: Requires installing the Lodash library as an external dependency.
Example:
import cloneDeep from "lodash/cloneDeep";
const original = { nested: { value: 42 } };
const deepCopy = cloneDeep(original);
deepCopy.nested.value = 99;
// original.nested.value stays 42
Custom Recursive Function
- Pros: Full control over copying logic; can be tailored for specialized data structures.
- Cons: Requires careful implementation to handle all possible cases (including cyclical references and special object types).
Example:
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map(deepClone);
const copy = {};
for (const key in obj) {
copy[key] = deepClone(obj[key]);
}
return copy;
}
const original = { arr: [1, 2, 3], info: { age: 22 } };
const deepCopy = deepClone(original);
deepCopy.info.age = 50;
// original.info.age remains 22
Choosing the Right Approach
Use a Shallow Copy when:
- You only need to clone top-level data.
- Performance is a priority.
- Shared references to nested structures are acceptable or unchanging.
Use a Deep Copy when:
- Your structure contains nested objects or arrays.
- Independence between the original and copy is required.
- You want to safeguard against accidental mutations.
- Immutability is critical (e.g., React state management patterns).
Summary
- Shallow Copy: Duplicates only the first layer of an object or array; nested structures remain as shared references.
- Deep Copy: Recursively duplicates everything — no shared references exist between original and copy.
- Recommendation: For performance-sensitive, flat data, shallow copy methods are often sufficient. When managing complex or deeply nested data, especially where immutability is important (such as in modern frameworks like React), deep copy techniques — such as
[structuredClone](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone), Lodash’scloneDeep, or a custom function—should be used to prevent subtle bugs and ensure data integrity.
Carefully selecting between these approaches, based on your data and application requirements, is crucial to writing robust, maintainable JavaScript code.
메타데이터
- post_id
- 8d6bedbe242f
- slug
- copy-that-mastering-shallow-and-deep-copy-in-javascript-8d6bedbe242f
- url
- https://medium.com/@atulj10unofficial/copy-that-mastering-shallow-and-deep-copy-in-javascript-8d6bedbe242f
- canonical_url
- https://medium.com/@atulj10unofficial/copy-that-mastering-shallow-and-deep-copy-in-javascript-8d6bedbe242f
- author_url
- https://medium.com/@atulj10unofficial
- status
- ok
- fetched_at
- 2026-07-18 21:27:51