Spread and copying
Overview
Assigning an object to another variable doesn’t copy it — both names point at the same object:
const a = { score: 1 };
const b = a;
b.score = 99;
a.score; // 99 — a changed tooThe same is true for arrays, and for objects passed into functions. Usually that’s fine. But when you want to change something without affecting the original — to keep an undo history, to compare old and new, or because a framework like React needs it — you need a real copy.
Copying with spread
The spread syntax ... copies properties into a new object or items into a new array:
const original = { theme: 'light', size: 'm' };
const copy = { ...original };
copy.theme = 'dark';
original.theme; // 'light' — unaffected
const list = [1, 2, 3];
const listCopy = [...list];
listCopy.push(4);
list; // [1, 2, 3]Other ways to copy you’ll meet: Object.assign({}, original) for objects, and list.slice() or Array.from(list) for arrays. Spread is the most common today.
Merging
const defaults = { theme: 'light', size: 'm' };
const choices = { size: 'l' };
const settings = { ...defaults, ...choices }; // { theme: 'light', size: 'l' }
const all = [...['a', 'b'], ...['c']]; // ['a', 'b', 'c']When two objects share a key, the one spread later wins. That makes “defaults, then overrides” a one-liner.
Updating one property
To make a copy with a change, spread first and then write the new value:
const user = { name: 'Asha', plan: 'free' };
const upgraded = { ...user, plan: 'pro' }; // ✓ plan: 'pro'
const wrong = { plan: 'pro', ...user }; // ✗ plan: 'free' — user's value came laterArrays: add, remove and replace without changing
| Goal | Changes the original | Returns a new array |
|---|---|---|
| Add to end | arr.push(x) |
[...arr, x] |
| Add to start | arr.unshift(x) |
[x, ...arr] |
| Remove an item | arr.splice(i, 1) |
arr.filter((_, j) => j !== i) or arr.toSpliced(i, 1) |
| Replace an item | arr[i] = x |
arr.with(i, x) |
| Sort | arr.sort() |
arr.toSorted() |
| Reverse | arr.reverse() |
arr.toReversed() |
The to… and with methods were added in 2023 and work in all current browsers.
Shallow vs deep
Spread copies only the top level. Nested objects are still shared:
const user = { name: 'Asha', prefs: { theme: 'light' } };
const copy = { ...user };
copy.prefs.theme = 'dark';
user.prefs.theme; // 'dark' — the nested object is sharedThe spread copied the reference to prefs, not the prefs object itself. There are two ways to deal with that.
Copy each level you change
When updating nested data, spread at every level along the path:
const updated = {
...user,
prefs: { ...user.prefs, theme: 'dark' },
};
user.prefs.theme; // 'light' — original untouched
updated.prefs.theme; // 'dark'This is the standard pattern in React and Redux code. Unchanged branches are shared (which is efficient); only the path to the change is new.
Deep copy everything
For a full, independent copy, use structuredClone:
const deep = structuredClone(user);
deep.prefs.theme = 'dark';
user.prefs.theme; // 'light'structuredClone handles nested objects, arrays, dates, Maps and Sets. It can’t copy functions or DOM elements — it throws if it meets one.
You may see an older trick, JSON.parse(JSON.stringify(obj)). It works for plain data, but turns dates into strings and silently drops undefined and functions. Prefer structuredClone.
Spread in other places
Spread works anywhere a list of values is expected:
Math.max(...[3, 9, 2]); // 9 — as function arguments
const chars = [...'hello']; // ['h', 'e', 'l', 'l', 'o']
const unique = [...new Set([1, 1, 2])]; // [1, 2]And ... in a pattern is the opposite — rest — gathering values up:
const { password, ...publicInfo } = user; // rest in destructuring
function log(...messages) {} // rest parameterWhy copy at all? Code that returns new objects instead of changing old ones is easier to reason about, and frameworks like React rely on it.
Freezing
If you want to make sure nobody changes an object, Object.freeze stops properties being added, removed or changed — but, like spread, it’s shallow:
const config = Object.freeze({ api: '/v1', limits: { max: 10 } });
config.api = '/v2'; // ignored (TypeError in strict mode)
config.limits.max = 99; // allowed — the nested object isn't frozenThe Equality and immutability topic explores this further.
Update without changing
Return a new settings object with theme set to 'dark', leaving the original untouched. Then write addTag(post, tag) that returns a new post with the tag added to its tags array — without changing the original post or its array.
function withDarkTheme(settings) {
// your code here
}
function addTag(post, tag) {
// your code here
}function withDarkTheme(settings) {
return { ...settings, theme: 'dark' };
}
function addTag(post, tag) {
return { ...post, tags: [...post.tags, tag] };
}Summary
- Assigning an object or array copies the reference, not the data.
{ ...obj }and[...arr]make shallow copies; later properties win when merging.- A shallow copy shares nested objects — copy each level you change, or deep-copy.
- Use
structuredClonefor a deep copy of nested data. - Prefer returning updated copies over changing data in place.