Copying objects or arrays in JavaScript can be done shallowly or deeply, depending on whether nested objects are duplicated or just referenced.
1️⃣ Shallow Copy
- Copies only the first level of the object
- Nested objects/arrays are still referenced, not duplicated
- Changes in nested objects affect the original
Example:
const original = {
name: "Alice",
address: { city: "Delhi", zip: 110001 }
};
// Shallow copy using spread operator
const shallowCopy = { ...original };
shallowCopy.name = "Bob";
shallowCopy.address.city = "Mumbai";
console.log(original.name); // "Alice" → top-level primitive unaffected
console.log(original.address.city); // "Mumbai" → nested object affected
- Key point: only the top-level is copied; nested objects share reference.
2️⃣ Deep Copy
- Creates a full independent copy, including nested objects
- Changes in the copy do not affect the original
Example 1: Using JSON.stringify (simple objects only)
const original = {
name: "Alice",
address: { city: "Delhi", zip: 110001 }
};
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.address.city = "Mumbai";
console.log(original.address.city); // "Delhi" → original remains unchanged
Example 2: Using structuredClone (modern JS)
const deepCopy2 = structuredClone(original);
deepCopy2.address.zip = 560001;
console.log(original.address.zip); // 110001 → original unaffected
- Supports nested objects, arrays, dates, maps, sets (structuredClone is better than JSON method)
Quick Comparison
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Level | Top-level only | All nested levels |
| Nested Objects | Shared reference | Fully duplicated |
| Methods | Spread ..., Object.assign() |
JSON.parse(JSON.stringify()), structuredClone() |
| Performance | Faster for large objects | Slower for deeply nested objects |
⚡ In short:
Use shallow copy for simple, top-level duplication, and deep copy when you need a completely independent object, especially if it contains nested objects or arrays.