Intermediate LevelJavaScript & TypeScript
How does deep cloning vs shallow cloning work in JavaScript (structuredClone, spread, JSON)?
❓ Interview Prompt: Compare Object.assign/spread (shallow copy) with structuredClone and custom recursive cloning (deep copy).
Shallow Copy ({ ...obj } / Object.assign()):
Copies top-level properties. Nested objects/arrays still share the same reference memory, so modifying nested properties mutates the original object!
Deep Copy (Independent Clone):
Recursively copies all levels of objects and arrays.
Deep Copy Options:
1
`structuredClone(obj)` (Modern Standard): Native browser API. Handles circular references, Date, Map, Set, ArrayBuffer.
2
`JSON.parse(JSON.stringify(obj))`: Legacy fallback. Fails on functions, undefined, Symbols, and circular references.
Code Implementation Example
javascript
const original = {
name: 'Alice',
details: { city: 'NYC' },
created: new Date()
};
// 1. Shallow Copy (Spread)
const shallow = { ...original };
shallow.details.city = 'London';
console.log(original.details.city); // "London" ❌ (Mutated original!)
// 2. Native Deep Copy (structuredClone)
const deep = structuredClone(original);
deep.details.city = 'Paris';
console.log(original.details.city); // "London" ✅ (Original unaffected!)
console.log(deep.created instanceof Date); // true ✅ (Preserves Date instance!)💡Shallow copy reference leaks vs native structuredClone deep copying.
🎯 Interview Key Takeaway
Use structuredClone() for deep copies of complex nested objects. Spread syntax only creates shallow copies.
#Cloning#structuredClone#Objects#Intermediate
Back to all JavaScript & TypeScript Questions→