Arrays
Spread ...
"Spreads out" an array or object to copy it or join it with others.
Why it exists
You often need a new array based on an old one: a copy before sorting, the old messages plus a new one, a Set back into an array. These used to need concat, slice() and Array.from, each with its own syntax. ... does all of it with one clear sign. And most importantly, it creates a new array or object without changing the original. React state handling is built on this.
Where it's used
- Add an item without changing the array:
[...messages, newMessage]in React. - Remove duplicates:
[...new Set(tags)]. - A copy before sorting:
[...items].sort(). - Update an object's field:
{ ...user, name: "Ann" }.
Syntax
[...array]
[...a, ...b]
{ ...object, property: value }
fn(...args)Examples
const a = [1, 2];
const b = [3];
[...a, ...b]; // → [1, 2, 3]
[...new Set([1, 1, 2])]; // → [1, 2]const messages = ["Hi"];
const next = [...messages, "How are you?"];
messages; // → ["Hi"]
next; // → ["Hi", "How are you?"]const defaults = { theme: "light", lang: "en" };
({ ...defaults, theme: "dark" }); // → { theme: "dark", lang: "en" }[..."cat"]; // → ["c", "a", "t"]
Math.max(...[3, 9, 2]); // → 9Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
... before a value inside [ ] iterates it like for...of and inserts the items one by one. So anything iterable can be spread: arrays, strings (into characters), Set, Map.
Inside { }, spread copies an object's own properties. If a property repeats, whichever is written later wins: { ...defaults, ...settings } — the settings override the defaults.
The copy is shallow: the array or object itself is copied, but nested objects stay shared. Changing copy[0].name changes the original too.
The same three dots in a function's parameters are rest: instead of spreading, they gather the remaining arguments into an array.
Traps
How it differs from…
array.push()push changes the existing array;
[...arr, x]creates a new one. React state, and anywhere data mustn't change in place, needs the second.Set[...new Set(arr)]is the shortest way to remove duplicates from an array.
When to pick something else
Don't copy an array with ... on every step of a loop — with big data that's slow (everything is copied each time). If the array may be changed, push is cheaper. For a deep copy you need structuredClone, not spread.