Object Reference & Copy
In JavaScript, objects are reference types, meaning that when you assign an object to another variable, both variables point to the same memory location. This can lead to unexpected changes if you modify one variable — since both refer to the same object.
To prevent this, developers often copy objects instead of referencing them.
Copying can be done in two main ways: Shallow Copy and Deep Copy.
Object Reference (By Memory Address)
When you assign one object to another variable, JavaScript doesn’t create a new object — it only copies the reference.
const obj1 = { name: "Alice" };
const obj2 = obj1; // Reference to the same object
obj2.name = "Bob";
console.log(obj1.name); // "Bob" (both point to same memory)
Shallow Copy
A shallow copy creates a new object but only copies the top-level properties.
If the object contains nested objects, they are still referenced, not duplicated.
Using Spread Operator (...
)
const user = { name: "John", address: { city: "Delhi" } };
const copy = { ...user };
copy.name = "Alice";
copy.address.city = "Mumbai";
console.log(user.address.city); // "Mumbai" (nested still linked)
Using Object.assign()
const user = { name: "John", address: { city: "Delhi" } };
const copy = Object.assign({}, user);
copy.address.city = "Pune";
console.log(user.address.city); // "Pune" (same issue)
Deep Copy
A deep copy duplicates an object and all of its nested objects, creating a completely independent copy.
Using structuredClone()
(ES2021+)
const user = { name: "John", address: { city: "Delhi" } };
const deepCopy = structuredClone(user);
deepCopy.address.city = "Goa";
console.log(user.address.city); // "Delhi" (independent)
Using JSON.parse(JSON.stringify())
const user = { name: "John", address: { city: "Delhi" } };
const deepCopy = JSON.parse(JSON.stringify(user));
deepCopy.address.city = "Bangalore";
console.log(user.address.city); // "Delhi"
Comparison Table
Method | Type | Nested Objects Copied? | Keeps Functions? | Best For |
---|---|---|---|---|
Assignment (= ) | Reference | No | Yes | Shared references |
Spread (... ) | Shallow | No | Yes | Simple objects |
Object.assign() | Shallow | No | Yes | Cloning top-level props |
structuredClone() | Deep | Yes | Yes | Modern deep copies |
JSON.parse(JSON.stringify()) | Deep | Yes | No | Simple data-only objects |
Real-World Example
const original = {
name: "Alice",
details: { city: "Delhi", pin: 110001 }
};
// Reference
const ref = original;
// Shallow copy
const shallow = { ...original };
// Deep copy
const deep = structuredClone(original);
ref.name = "Bob";
shallow.details.city = "Mumbai";
deep.details.city = "Goa";
console.log(original.name); // "Bob" (same reference)
console.log(original.details.city); // "Mumbai" (shared nested)
console.log(deep.details.city); // "Goa" (independent copy)