“I changed the copy, so why did the original change too?” This is one of the most common surprises in JavaScript. The reason is that objects and arrays are stored by reference: assigning one to a new variable does not copy it. This lesson explains references, the difference between shallow and deep copies, and the right tool for each job, including the modern structuredClone().
In this lesson you will learn
- Values versus references
- Shallow copies with spread,
Object.assignandslice - Why nested objects are still shared after a shallow copy
- Deep copies with
structuredClone() - The limits of the JSON trick and of
Object.freeze
You should know objects, arrays and spread syntax.
References and Shallow Copies
"use strict";
// Primitives are copied by value; objects are shared by reference
let a = 5;
let b = a;
b = 10;
console.log(a, b); // 5 10: separate copies
const original = { name: "Rina", marks: [80, 75] };
const sameObject = original; // NOT a copy, just a second name
sameObject.name = "Mina";
console.log(original.name); // Mina: both names point at one object
console.log(sameObject === original); // true
// Shallow copies: spread, Object.assign, slice and Array.from
const s1 = { ...original };
const s2 = Object.assign({}, original);
s1.name = "Rina";
console.log(original.name, s1.name, s1 === original); // top level is separate
// ...but nested objects are still shared
s2.marks.push(99);
console.log(original.marks); // [80, 75, 99]: the inner array was shared!
const list = [1, 2, 3];
const listCopy = [...list]; // same idea for arrays
listCopy.push(4);
console.log(list, listCopy);
// Comparing objects compares references, not contents
console.log({ x: 1 } === { x: 1 });
console.log(JSON.stringify({ x: 1 }) === JSON.stringify({ x: 1 })); // a quick content check
Output
5 10
Mina
true
Mina Rina false
[ 80, 75, 99 ]
[ 1, 2, 3 ] [ 1, 2, 3, 4 ]
false
true
- Primitive values (numbers, strings, booleans) are copied when assigned, so changing
bleavesaalone. - A variable holding an object holds a reference, like an address.
sameObject = originalcopies the address, so both names lead to the same object. { ...original }andObject.assign({}, original)create a new object and copy each top-level property. Changings1.namedoes not affect the original.- But
marksis itself an array, and only its reference was copied. Pushing throughs2.markschanged the one array that all three objects share. This is what shallow means. ===on objects asks “is this the same object?”, not “do they contain the same things?”, so two identical-looking literals are not equal.
Deep Copies with structuredClone
"use strict";
// structuredClone makes a DEEP copy: nested objects are copied too
const student = {
name: "Rina",
marks: { maths: 80, physics: 75 },
subjects: ["Maths", "Physics"],
joined: new Date(Date.UTC(2025, 0, 1)),
clubs: new Set(["Science", "Debate"]),
};
const deep = structuredClone(student);
deep.marks.maths = 95;
deep.subjects.push("ICT");
deep.clubs.add("Chess");
console.log(student.marks.maths, student.subjects.length, student.clubs.size); // unchanged
console.log(deep.joined instanceof Date, deep.clubs instanceof Set); // types kept
// The old JSON trick also deep-copies, but loses some types
const viaJson = JSON.parse(JSON.stringify(student));
console.log(typeof viaJson.joined, viaJson.clubs); // Date became a string, Set became {}
// structuredClone cannot copy functions (or DOM elements)
try {
structuredClone({ greet() { return "hi"; } });
} catch (err) {
console.log(err.name + ": functions cannot be cloned");
}
// Freezing stops changes, but it is also shallow
const settings = Object.freeze({ theme: "dark", sizes: [12, 14] });
try { settings.theme = "light"; } catch (err) { console.log(err.name + ": settings is frozen"); }
settings.sizes.push(16); // the inner array is not frozen
console.log(settings.theme, settings.sizes);
Output
80 2 2
true true
string {}
DataCloneError: functions cannot be cloned
TypeError: settings is frozen
dark [ 12, 14, 16 ]
structuredClone(value)copies the whole structure, every level down, so changes to the clone’s nested objects, arrays and sets do not touch the original.- It keeps many built-in types, including
Date,Map,Set, typed arrays and even circular references. - The older
JSON.parse(JSON.stringify(x))trick turns dates into strings, sets and maps into empty objects, and drops functions andundefined. structuredClonethrows aDataCloneErrorfor functions and DOM elements. Class instances are copied as plain objects, losing their methods.Object.freezeprevents changes to an object’s own properties (throwing in strict mode), but like spread it is shallow: the nested array could still be changed.
Which Copy Do I Need?
| Situation | Use |
|---|---|
| Flat object or array (no nesting) | { ...obj }, [...arr] |
| Update one property, keep the rest | { ...obj, name: "New" } |
| Update a nested property | { ...obj, marks: { ...obj.marks, maths: 95 } } |
| Fully independent copy of data | structuredClone(obj) |
| Copy that keeps class methods | Write a clone() method in the class |
Array methods such as map, filter, toSorted and toReversed also return new arrays, but the objects inside are still shared.
Common Mistakes
- Assuming
=copies an object, then changing the “copy”. - Assuming spread is deep and changing a nested array.
- Using
sort()on a shared array, which changes it in place for everyone; usetoSorted()or copy first. - Using the JSON trick on data with dates and getting strings back.
Practice Exercises
Exercise 1. Without changing user, create updated where address.city is “Khulna”.
const user = { name: "Rina", address: { city: "Dhaka", zip: "1207" } };
Show answer
const updated = { ...user, address: { ...user.address, city: "Khulna" } };
console.log(user.address.city, updated.address.city); // Dhaka Khulna
Exercise 2. Predict the output, then explain it.
const a = [[1], [2]];
const b = [...a];
b[0].push(9);
b.push([3]);
console.log(a.length, a[0]);
Show answer
2 [ 1, 9 ]. b is a new outer array, so pushing [3] does not affect a‘s length, but the inner arrays are shared, so a[0] sees the 9.
Frequently Asked Questions
Where can I use structuredClone?
It is built into all modern browsers and into Node.js 17 and later, so no library is needed. Older code often used a library function such as lodash cloneDeep for the same job.
Why do frameworks like React care about copies?
They detect changes by comparing references. If you change an object in place, the reference stays the same and the screen may not update, so they expect you to create new objects with spread instead.
Summary
- Assigning an object copies the reference, not the object.
- Spread,
Object.assignandslicemake shallow copies: nested parts stay shared. structuredClonemakes deep copies and keeps dates, maps and sets.Object.freezeis shallow, just like spread.
