Copying and Comparing Objects
A variable that holds an object doesn't contain the object itself; it holds a reference, a pointer to where the object lives in memory. Assigning that variable to another, or passing it to a function, copies the reference, not the object, so both names see the same object. To get an independent copy you must ask for one: a shallow copy duplicates the top level, and a deep copy duplicates everything inside. Getting this right is what keeps "I only changed the copy" from changing the original.
In One Minute
- Primitives are copied by value; objects (including arrays) are shared by reference.
const b = amakesbpoint to the same object. Changes through either name are visible through both.- Shallow copy:
{ ...obj },Object.assign({}, obj),[...arr]. Nested objects are still shared. - Deep copy:
structuredClone(obj)copies everything, including nested objects, Dates, Maps and Sets. ===compares references. To compare contents, compare the properties (or use a deep-equal helper).
Values vs References
let a = 120;
let b = a;
b = 200;
console.log(a, b);
const s1 = { name: "Navika", balance: 120 };
const s2 = s1;
s2.balance = 200;
console.log(s1.balance, s2.balance);
console.log(s1 === s2);120 200
200 200
trueExplanation: for the number, b = a copied the value 120 into b; changing b later didn't touch a. For the object, s2 = s1 copied the reference, so s1 and s2 are two names for one object. Changing it through s2 changed what s1 sees.
| Primitives | Objects (and arrays, functions) | |
|---|---|---|
| A variable holds | The value itself | A reference to the object |
b = a copies | The value | The reference |
=== compares | Values | References (identity) |
| Can be changed in place | No (immutable) | Yes |
The same rule applies to function arguments: passing an object gives the function a reference to the same object (see the parameters lesson).
Shallow Copies
A shallow copy creates a new object and copies each top-level property into it. Primitive values are copied; object values are copied as references.
const original = { name: "Advitha", balance: 45, payments: [45] };
const spreadCopy = { ...original };
const assignCopy = Object.assign({}, original);
spreadCopy.balance = 0;
console.log(original.balance, spreadCopy.balance);
spreadCopy.payments.push(100);
console.log(original.payments);
console.log(spreadCopy.payments === original.payments);
console.log(assignCopy.payments === original.payments);45 0
[45, 100]
true
trueExplanation: balance is a number, so each copy has its own. payments is an array, so the copies hold references to the same array: pushing through spreadCopy changed the original's payments too.
| Way | Arrays | Objects | Notes |
|---|---|---|---|
| Spread | [...arr] | { ...obj } | Most common |
Object.assign | n/a | Object.assign({}, obj) | Runs setters on the target |
slice / Array.from | arr.slice() | n/a | Older style |
Deep Copies with structuredClone
A deep copy duplicates the object and everything it contains, all the way down. structuredClone is the built-in way, available in all modern browsers and Node.js:
const original = {
name: "Srihitha",
contact: { city: "San Francisco" },
payments: [{ amount: 200 }],
due: new Date("2026-02-01T00:00:00"),
tags: new Set(["sibling"]),
};
const copy = structuredClone(original);
copy.contact.city = "Dallas";
copy.payments[0].amount = 999;
copy.tags.add("late");
console.log(original.contact.city, original.payments[0].amount, original.tags.size);
console.log(copy.due instanceof Date, copy.due.getTime() === original.due.getTime());San Francisco 200 1
true truestructuredClone handles nested objects and arrays, Date, Map, Set, typed arrays, and even circular references (an object that refers to itself). It can't copy functions, DOM elements, or class identity: a class instance comes back as a plain object without its methods.
try {
structuredClone({ format: () => "x" });
} catch (err) {
console.log(err.name);
}
class Account {
constructor() { this.balance = 10; }
describe() { return "account"; }
}
const clone = structuredClone(new Account());
console.log(clone.balance, typeof clone.describe);DataCloneError
10 undefinedThe Older JSON Trick
Before structuredClone, people deep-copied with JSON.parse(JSON.stringify(obj)). It works for plain data but silently damages anything else:
const original = { when: new Date("2026-01-05T10:00:00"), missing: undefined, ratio: NaN };
const copy = JSON.parse(JSON.stringify(original));
console.log(typeof copy.when);
console.log("missing" in copy);
console.log(copy.ratio);string
false
nullDates become strings, undefined properties vanish, and NaN becomes null. Use structuredClone.
Comparing Objects
=== asks "are these the same object?", not "do they have the same contents?":
const a = { name: "Navika", grade: 9 };
const b = { name: "Navika", grade: 9 };
console.log(a === b);
console.log(a === a);
function shallowEqual(x, y) {
const keysX = Object.keys(x);
const keysY = Object.keys(y);
return keysX.length === keysY.length && keysX.every((k) => Object.is(x[k], y[k]));
}
console.log(shallowEqual(a, b));
console.log(shallowEqual({ list: [1] }, { list: [1] }));false
true
true
falseExplanation: shallowEqual compares the top-level properties. It returns false for the last pair because the two list arrays are different objects. A full deep equal compares recursively; Node.js has one built in (assert.deepStrictEqual and util.isDeepStrictEqual), and testing libraries provide their own. JSON.stringify(a) === JSON.stringify(b) works only for plain data with properties in the same order.
In Practice
The Fee Tracker keeps an undo history. Every change produces a new state with structural sharing: unchanged parts are reused (shallow copies), changed parts are new. Saving a snapshot for a backup uses a deep copy:
const history = [];
let state = {
students: [{ name: "Navika", balance: 450 }, { name: "Advitha", balance: 45 }],
settings: { currency: "USD" },
};
function recordPayment(current, name, amount) {
return {
...current,
students: current.students.map((s) => (s.name === name ? { ...s, balance: s.balance - amount } : s)),
};
}
history.push(state);
state = recordPayment(state, "Navika", 200);
console.log(state.students[0].balance, history[0].students[0].balance);
console.log(state.settings === history[0].settings);
console.log(state.students[1] === history[0].students[1]);
const backup = structuredClone(state);
console.log(backup.settings === state.settings);250 450
true
true
falseThe old state is intact (450), unchanged parts (settings, Advitha's record) are shared at no cost, and the backup shares nothing. This is how frameworks such as React and Redux expect state to be updated.
Common Mistakes
Thinking const copy = obj copies. It shares. Use spread or structuredClone.
Changing nested data after a shallow copy. The original changes too. Spread each level you change, or deep-copy.
Comparing objects with === to check contents. It checks identity. Compare properties.
Deep-copying with JSON. Dates, undefined, NaN, Maps and Sets are damaged. Use structuredClone.
Interview Corner
What is the difference between a shallow and a deep copy?
A shallow copy creates a new top-level object whose properties are copied by value, so nested objects are shared references. A deep copy recursively duplicates nested objects, so the copy and the original share nothing. In JavaScript: spread or Object.assign for shallow, structuredClone for deep (no functions or class prototypes).
Is JavaScript pass-by-reference?
No, it is always pass-by-value. For objects, the value passed is a reference, so the function can mutate the shared object but can't make the caller's variable point to a different object. This is sometimes called "call by sharing".
What does this print?
Show solution
const a = { n: 1, inner: { m: 1 } };
const b = { ...a };
b.n = 2;
b.inner.m = 2;
const c = structuredClone(a);
c.inner.m = 3;
console.log(a.n, a.inner.m, c.inner.m);1 2 3b.n is a top-level copy, so a.n stays 1. b.inner is shared with a.inner, so a.inner.m becomes 2. c is a deep copy, so setting it to 3 leaves a alone.
Practice
Challenge: Write updateCity(student, city) that returns a new student with contact.city changed, without changing the original and without deep-copying the whole object.
Show solution
function updateCity(student, city) {
return { ...student, contact: { ...student.contact, city } };
}
const navika = { name: "Navika", contact: { city: "Dallas", phone: "2145550100" }, fees: [400] };
const moved = updateCity(navika, "Austin");
console.log(navika.contact.city, moved.contact.city, moved.contact.phone);
console.log(moved.fees === navika.fees);Dallas Austin 2145550100
trueKey Takeaways
| Need | Use |
|---|---|
| Share | const b = a |
| Shallow copy | { ...obj }, [...arr] |
| Deep copy | structuredClone(obj) |
| Same object? | a === b |
| Same contents (Node.js) | util.isDeepStrictEqual(a, b) |
Was this tutorial helpful?