Difference between shallow copy and deep copy in Javascript
Shallow copy
Only copies the first level; nested objects still share references with the original.
- Top-level properties (primitives) → copied by value → safe, changes don’t affect the original.
- Nested properties (objects/arrays) → copied by reference in shallow copy → modifying them also affects the original.
- Shallow: spread
{ ...obj }
,Object.assign()
,Array.slice()
.
Deep copy
Copies all levels; nested objects are also duplicated, making it fully independent.
- Deep copy duplicates all levels → no shared references, even for nested.
- Deep:
structuredClone()
,JSON.parse(JSON.stringify())
,lodash.cloneDeep()
.
const original = {
name: "Alice",
address: { city: "Jakarta" }
};
// Shallow copy
const shallow = { ...original };
shallow.name = "Bob"; // top-level → SAFE
console.log(original.name); // "Alice"
shallow.address.city = "Bandung"; // nested → DANGER
console.log(original.address.city); // "Bandung" (affected)
// Deep copy
const deep = JSON.parse(JSON.stringify(original));
deep.address.city = "Surabaya";
console.log(original.address.city); // "Bandung" (unchanged)