← All posts
postApril 11, 2026
Deep vs Shallow Copy
#javascript#objects#cloning#interview
What is the difference between a shallow copy and a deep copy in JavaScript? How do you create each?
**Shallow copy**: copies own properties one level deep. Nested objects/arrays still reference the same memory. ```js const a = { x: 1, nested: { y: 2 } }; const b = { ...a }; // shallow b.nested.y = 99; // also changes a.nested.y! ``` **Deep copy**: recursively copies all nested structures — fully independent. ```js // Modern built-in (no functions, undefined, or circular refs) const c = structuredClone(a); // ES2022+ // Older trick (JSON only — loses functions, Dates become strings) const d = JSON.parse(JSON.stringify(a)); ``` Use structuredClone for most cases. Use a library like lodash.cloneDeep for complex objects with Dates, Maps, etc.