Explain it simply
Explain it simply
Think of a deck of cards. Spread is dealing the deck out onto the table one card at a time. Writing [...cards, newCard] lays out the old cards, adds one more and gives you a brand-new deck, while the original deck stays exactly as it was.
Rest is the reverse. From the cards scattered on the table, you take the first one for yourself and gather everything left over back into a single pile. The symbol is the same three dots in both cases; where you write them decides whether they spread or gather.
Problem → Why → Solution
The problem: changing the original while thinking you copied it
An app gives every new user a set of default settings. A developer writes const settings = defaults and then switches theme to "dark" for one user. But = does not copy the object; it just gives the same object a second name.
The result: every user who signs up afterwards starts in dark mode. The bug report only says "settings sometimes change by themselves", which is hard to trace. Functions that take a variable number of inputs have a similar old pain: the arguments object is not a real array, so methods like reduce are not available on it.
const defaults = { theme: "light", fontSize: 14 };
function settingsFor(user) {
const settings = defaults; // not a copy: same object
if (user.likesDark) settings.theme = "dark";
return settings;
}
settingsFor({ likesDark: true });
console.log(defaults.theme); // "dark" - every later user is affected
function oldSum() {
return arguments.reduce((a, b) => a + b); // TypeError: not a function
}Why does this happen?
In JavaScript, object and array variables do not hold the value itself; they hold a reference to it. = copies only that reference, so both names edit the same object. { ...defaults } spreads the properties into a new object, which fixes the bug. arguments is only array-like, while a rest parameter such as ...numbers gives you a real array.
Core concept: spreading or gathering
Each time you see ..., ask: does JavaScript expect values here, or names? Where values are expected (an array literal, an object literal, the arguments of a call), it is spread and it expands. Where names are expected (a parameter list or a destructuring pattern), it is rest and it gathers.
| Where | Job | Example |
|---|---|---|
| Array literal | Spread: expands items | [...a, ...b] |
| Function call | Spread: expands arguments | Math.max(...nums) |
| Object literal | Spread: copies properties | { ...obj, id: 2 } |
| Parameter list | Rest: gathers arguments | function f(...args) |
| Destructuring | Rest: gathers the remainder | const [x, ...more] = arr |
Array spread works with any iterable: arrays, strings, Sets and Maps. That is why [...new Set(list)] gives you an array without duplicates and [..."hi"] gives ["h", "i"]. A plain object is not iterable, so [...{ a: 1 }] throws a TypeError. Object spread, on the other hand, copies an object's own enumerable properties.
In object spread, when two properties share a name, the one written later wins. So write the defaults first and the overrides after them. A rest element must always come last, and there can be only one; anywhere else it is a SyntaxError.
Most important of all, spread makes a shallow copy. Only the top level is new; nested objects and arrays are still shared by reference. To update nested data, spread each level you change, or use structuredClone() when you truly need a deep copy.
Spreading null or undefined
Object spread quietly skips null and undefined: { ...null } is just {}, so { ...defaults, ...options } is safe even when options was never passed. Array spread is stricter. [...null] and [...undefined] throw a TypeError because neither is iterable, so guard a possibly missing list with [...(list ?? [])].
- Look at where the ... sits
- Where values go: spread
- Where names go: rest
- Only the top level is new
Read an object merge from left to right: the rightmost property is written last, so it wins.
General pattern
// Spread: expand values
const newArray = [...arrayA, extraItem, ...arrayB];
const newObject = { ...baseObject, keyToOverride: newValue };
someFunction(...argsArray);
// Rest: gather values
function fn(firstParam, ...restParams) { /* restParams is an array */ }
const [head, ...tail] = someArray;
const { unwanted, ...kept } = someObject;Inside literals and calls, ... is spread and expands. Inside parameter lists and destructuring patterns, it is rest and gathers whatever is left. A rest element always comes last.
Run spread and rest in six places
The code below uses spread in three places, rest in two, and ends with a part that shows the danger of a shallow copy. The last line edits copy but prints original.tags; decide what you expect there before running it.
// Spread in an array literal: copy and extend
const base = [1, 2, 3];
const extended = [...base, 4, 5];
console.log(extended);
// Spread in a function call: one array becomes separate arguments
console.log(Math.max(...base));
// Spread in an object literal: the property written last wins
const defaults = { theme: "light", fontSize: 14 };
const userPrefs = { fontSize: 18 };
const settings = { ...defaults, ...userPrefs };
console.log(settings);
// Rest parameter: gather any number of arguments into an array
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4));
// Rest in destructuring: take one property, keep the remainder
const { theme, ...others } = settings;
console.log(theme, others);
// Spread copies are shallow: nested arrays are still shared
const original = { name: "Ana", tags: ["js"] };
const copy = { ...original };
copy.tags.push("css");
console.log(original.tags);Code breakdown
- Copy and extend an array
const extended = [...base, 4, 5];The items of base are laid out in a new array, then 4 and 5 are added. base itself remains [1, 2, 3].
- Array to arguments
console.log(Math.max(...base));Math.max wants separate number arguments, not an array. Spread turns the call into Math.max(1, 2, 3), which returns 3.
- Last property wins
const settings = { ...defaults, ...userPrefs };defaults is spread first and userPrefs second, so fontSize 18 replaces 14. Swap the order and the user's choice would be lost.
- Rest parameter
function sum(...numbers) {All arguments of sum(1, 2, 3, 4) are gathered into numbers, a real array, so reduce works on it directly.
- Rest in a pattern
const { theme, ...others } = settings;theme is pulled out on its own and the remaining properties (fontSize) go into a new object called others. It is a neat way to drop one property.
- Shared nested array
copy.tags.push("css");copy is a new object, but its tags still points at the same array, so "css" shows up in original.tags too.
[ 1, 2, 3, 4, 5 ]
3
{ theme: 'light', fontSize: 18 }
10
light { fontSize: 18 }
[ 'js', 'css' ]Updating nested data immutably
To avoid the shallow-copy trap, spread every level along the path you are changing. The code below changes notifications.email by spreading the outer object once and notifications once. Parts you do not touch, such as profile, keep sharing the same reference, which also saves memory.
const state = {
profile: { name: "Ana" },
notifications: { email: true, sms: false },
};
const next = {
...state,
notifications: { ...state.notifications, email: false },
};
console.log(state.notifications.email, next.notifications.email);
console.log(next.profile === state.profile); // untouched part is shared
console.log(structuredClone(state).profile === state.profile);Do not spread huge arrays into a call
Math.max(...values) passes every item as a separate argument. With millions of items it can exceed the engine's limit and throw a RangeError. Where data can be large, use values.reduce((max, v) => Math.max(max, v), -Infinity) instead.
In real projects
In real projects
UI libraries such as React and Redux expect you to build a new object instead of editing state in place, because they detect changes by comparing references. That is why setUser({ ...user, name: "Mya" }) and setItems([...items, newItem]) appear everywhere. Deleting an item uses filter, and updating one combines map with spread.
Configuration systems layer settings the same way: const config = { ...defaults, ...fileConfig, ...envConfig }. The further right, the higher the priority, so environment variables beat the config file and the file beats the defaults. It is worth pinning that order down with a test.
Rest parameters show up in wrappers like logger(level, ...messages) and in debounce or retry helpers that forward everything with fn(...args). Writing const { password, ...safeUser } = user to strip a field before sending a user object back from an API is another very common use.
Common mistakes
Common mistakes
Merging in the wrong order
Writing { ...userPrefs, ...defaults } means the defaults always overwrite whatever the user chose; the user changes a setting and nothing happens. Put defaults on the left and overrides on the right.
Assuming spread makes a deep copy
After const copy = { ...state }, calling copy.items.push(x) also changes state.items, and a UI library may not re-render because the reference never changed. Spread every nested level you modify, or use structuredClone().
Putting rest anywhere but last
function f(...items, last) and const [...start, end] = arr are both SyntaxErrors: rest means "everything that is left", so nothing can follow it. Use arr.at(-1) when you need the last item.
Spreading an object into an array
[...user] throws a TypeError because a plain object is not iterable. If you want an object's values as an array, use Object.values(user) or Object.entries(user).
Mini challenge
Merge settings without mutating anything
Write one function that merges default settings with any number of override objects, and another that updates the nested notifications. Neither may change any of its input objects.
- mergeSettings(defaults, ...overrides) applies the overrides from left to right
- setNotification(settings, channel, enabled) builds a new notifications object too
- withoutSecrets(settings) removes apiKey using rest destructuring
- Finally print defaults to show it was never changed
const defaults = {
theme: "light",
language: "en",
apiKey: "secret-123",
notifications: { email: true, sms: false },
};
function mergeSettings(defaults, ...overrides) {
// TODO: start from a copy of defaults and spread each override over it
}
function setNotification(settings, channel, enabled) {
// TODO: return a new object whose notifications is also a new object
}
function withoutSecrets(settings) {
// TODO: use rest destructuring to leave apiKey out
}
// TODO: merge { theme: "dark" } and { language: "my" },
// turn sms on, strip the secret, and print the resultsExpected: The merged settings show theme dark, language my and sms true; the public version has no apiKey; and defaults is still light, en, with sms false.
Show hint
A reduce such as overrides.reduce((acc, o) => ({ ...acc, ...o }), { ...defaults }) works well. For the nested update, use a computed key: notifications: { ...settings.notifications, [channel]: enabled }.
Show solution
const defaults = {
theme: "light",
language: "en",
apiKey: "secret-123",
notifications: { email: true, sms: false },
};
function mergeSettings(defaults, ...overrides) {
return overrides.reduce((acc, override) => ({ ...acc, ...override }), { ...defaults });
}
function setNotification(settings, channel, enabled) {
return {
...settings,
notifications: { ...settings.notifications, [channel]: enabled },
};
}
function withoutSecrets(settings) {
const { apiKey, ...publicSettings } = settings;
return publicSettings;
}
const merged = mergeSettings(defaults, { theme: "dark" }, { language: "my" });
const updated = setNotification(merged, "sms", true);
console.log(withoutSecrets(updated));
console.log("defaults:", defaults.theme, defaults.language, defaults.notifications);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- ... is spread where values are expected and rest where names are expected
- In object spread the later property wins, so write defaults first and overrides last
- A rest parameter gives a real array, and a rest element must always be last
- Spread makes shallow copies, so spread every nested level you change
MDN — JavaScript Guide — MDN Web Docs