Copying Objects
Making a genuine copy of an object takes a deliberate step, and the easy ways only copy one level deep.
Spread and Object.assign make a shallow copy: top-level values are copied, nested objects are still shared. structuredClone copies all the way down. Spread also merges objects, with later values winning.
EXERCISE
1Spread: A Copy One Level Deep
Three dots inside a new object literal copy every property of an existing one into it.
Making a copy:
const original = { name: "Ada", age: 36 };
const copy = { ...original };
copy.age = 37;
console.log(original.age); // 36 <- safe
console.log(copy.age); // 37
console.log(original === copy); // false genuinely different objects
Copying with a change, which is the everyday use:
const user = { id: 1, name: "Ada", role: "editor" };
const promoted = { ...user, role: "admin" };
console.log(promoted); // { id: 1, name: 'Ada', role: 'admin' }
console.log(user.role); // editor <- untouched
The spread comes first and the override after, because later wins.
Order matters:
const defaults = { theme: "dark", fontSize: 14 };
const chosen = { fontSize: 18 };
console.log({ ...defaults, ...chosen });
// { theme: 'dark', fontSize: 18 } chosen wins, which is right
console.log({ ...chosen, ...defaults });
// { theme: 'dark', fontSize: 14 } defaults win, which is wrong
The same syntax works on arrays:
const items = [1, 2, 3];
const copy = [...items];
copy.push(4);
console.log(items); // [ 1, 2, 3 ]
console.log(copy); // [ 1, 2, 3, 4 ]
const combined = [...items, ...copy];
console.log(combined.length); // 7
Object.assign does the same job, in older syntax:
const copy2 = Object.assign({}, original, { age: 37 });
console.log(copy2); // { name: 'Ada', age: 37 }
// The empty {} is the target. Miss it out and you overwrite
// `original` instead of copying it, which is a real bug.
Pro Tip:
{ ...thing, field: newValue }is one of the most-used lines in modern JavaScript, because updating without changing the original is how React state, Redux reducers and most data handling now work. Learn to read it as "everything from thing, and then this field replaced".
EXERCISE
2Shallow Means One Level Only
A spread copies the top level and shares everything below it, which is the detail that turns a safe-looking copy into a shared one.
The problem:
const original = {
name: "Ada",
address: { city: "London" },
};
const copy = { ...original };
copy.name = "Grace";
copy.address.city = "New York";
console.log(original.name); // Ada <- copied, safe
console.log(original.address.city); // New York <- SHARED, changed
name was a string, so its value was copied. address was an object, so only its address was copied, and both objects point at the same one.
The same with arrays inside:
const template = { tags: [] };
const a = { ...template };
const b = { ...template };
a.tags.push("urgent");
console.log(b.tags); // [ 'urgent' ] one array, two objects
Copying a nested level by hand:
const original = {
name: "Ada", address: { city: "London" }
};
const copy = {
...original,
address: { ...original.address }, // copy that level too
};
copy.address.city = "New York";
console.log(original.address.city); // London <- safe now
structuredClone copies all the way down:
const original = {
name: "Ada",
address: { city: "London", tags: ["home"] },
};
const deep = structuredClone(original);
deep.address.city = "New York";
deep.address.tags.push("work");
console.log(original.address.city); // London
console.log(original.address.tags); // [ 'home' ]
// Built into modern browsers and Node. It handles dates, maps
// and sets correctly, and it refuses to copy functions.
"Shallow" is not a warning, it is a description: one level. For a flat object of strings and numbers a spread is a complete copy. The moment a property holds an object or an array, that property is still shared, and the bug will surface somewhere that looks unrelated.
EXERCISE
3Merging, Defaults and Picking Fields
Spread does more than copy, and three small patterns built on it cover most day-to-day object work.
Applying defaults:
const defaults = { theme: "dark", fontSize: 14, showTips: true };
function makeSettings(options) {
return { ...defaults, ...options };
}
console.log(makeSettings({ fontSize: 18 }));
// { theme: 'dark', fontSize: 18, showTips: true }
console.log(makeSettings({}));
// { theme: 'dark', fontSize: 14, showTips: true }
A warning about undefined:
const options = { fontSize: undefined };
console.log({ ...defaults, ...options });
// { theme: 'dark', fontSize: undefined, showTips: true }
// An explicit undefined overwrites. Spread does not skip it.
// Use ?? when that matters:
const fontSize = options.fontSize ?? defaults.fontSize;
console.log(fontSize); // 14
Removing a field, using rest:
const user = { id: 1, name: "Ada", password: "secret" };
const { password, ...safe } = user;
console.log(safe); // { id: 1, name: 'Ada' }
console.log(user.password); // secret <- original untouched
The ...safe collects everything that was not named. This is rest, and it is spread's mirror image.
Updating one item in an array of objects:
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
];
const updated = users.map((user) =>
user.id === 2 ? { ...user, name: "Grace Hopper" } : user,
);
console.log(updated[1].name); // Grace Hopper
console.log(users[1].name); // Grace <- original list intact
That last pattern, map with a ternary and a spread, is how a single item in a list gets updated without changing the original list. It appears in essentially every codebase, and it is worth reading slowly once: keep every user as it was, except the one whose id matches, which becomes a copy with one field changed.
