JavaScript Intermediate
What is the difference between shallow copy and deep copy in JavaScript? How do you implement them?
Core Difference
| Shallow Copy | Deep Copy | |
|---|---|---|
| Top-level properties | Copies value | Copies value |
| Nested objects/arrays | Shares reference | Recursively copies new objects |
| Modifying nested content | Affects original | Does not affect original |
Shallow Copy
Method 1: Object.assign()
const original = { a: 1, b: { c: 2 } };
const copy = Object.assign({}, original);
copy.b.c = 99;
console.log(original.b.c); // 99 (original is affected!)
Method 2: Spread Operator
const copy = { ...original };
const arrCopy = [...originalArr];
Method 3: Array.prototype.slice()
const copy = originalArr.slice();
Deep Copy
Method 1: JSON.parse(JSON.stringify()) (simplest, but with limitations)
const original = { a: 1, b: { c: [1, 2, 3] } };
const deep = JSON.parse(JSON.stringify(original));
deep.b.c.push(4);
console.log(original.b.c); // [1, 2, 3] (unaffected)
Limitations:
- Cannot handle
undefined,function, orSymbol - Cannot handle circular references (throws an error)
- Cannot handle
Date,Map,Set, and other special objects
Method 2: structuredClone() (ES2022, recommended)
const deep = structuredClone(original);
Supports more data types and handles circular references.
Method 3: Recursive Manual Implementation
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(deepClone);
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, deepClone(v)])
);
}
Method 4: Third-party Library
import cloneDeep from 'lodash/cloneDeep';
const deep = cloneDeep(original);
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
