Deep vs Shallow Copies
Overview
This is one of the most critical concepts in JavaScript. Primitive types (Strings, Numbers, Booleans) are stored by Value. Objects and Arrays are stored by Reference (memory address).
If you write const objB = objA, you did NOT copy the object! You just created a second variable pointing to the exact same memory address. If you change objB, objA also changes!
To safely duplicate an object, you must perform a Shallow Copy (copies top-level properties) or a Deep Copy (copies all nested objects recursively).
Syntax
const person1 = { name: "Kartik" };
const person2 = person1; // Just copies the memory address!
person2.name = "Aman";
console.log(person1.name); // "Aman" - The original was mutated!const original = { name: "Kartik", nested: { age: 22 } };
// Safely creates a brand NEW object in memory
const shallow = { ...original };
shallow.name = "Aman";
console.log(original.name); // "Kartik" (Safe!)
// DANGER: The nested object inside was NOT copied!
shallow.nested.age = 99;
console.log(original.nested.age); // 99 (Mutated!)// ES2022 introduced a native deep copy method!
const original = { name: "Kartik", nested: { age: 22 } };
const deepCopy = structuredClone(original);
deepCopy.nested.age = 99;
console.log(original.nested.age); // 22 (Completely Safe!)Common Pitfalls
- Using
JSON.parse(JSON.stringify(obj))for deep copies. While this was the industry standard for a decade, it is slow and silently destroys complex data types likeDateobjects,Functions,Maps, andSets. Use the nativestructuredClone()instead.
Interview Questions
{} === {} evaluate to false?Because objects are compared by their memory reference, not their value. When you define two empty objects {}, they are created in two completely separate spaces in the computer's memory. Therefore, their memory addresses are not strictly equal.
A shallow copy duplicates the outermost layer of an object into new memory. However, if any properties are themselves objects or arrays, the references to those inner objects are just copied, meaning the inner objects remain linked.
Real-World Example
When updating state in React, you MUST provide a brand new object reference, otherwise React will not trigger a re-render. You use the spread operator to shallow copy the previous state.
setUser(prev => ({ ...prev, name: 'New Name' }));Check Your Knowledge
Test your understanding of Deep vs Shallow Copies with these quick questions.