Spread and Rest
Three little dots.
Three little dots do two opposite jobs in JavaScript. Spread unpacks an array into separate values. Rest packs separate values into an array. Both are used all the time.

- Three dots
- Spread unpacks
- Rest packs
Spreading and gathering
Spread copies the items of one array into a new one, so we can combine arrays, or add items, without changing the originals. Spreading into math dot max passes each number separately. And in a function's parameters, rest gathers any number of arguments into an array. Run it.
const a = [1, 2];
const b = [3, 4];
const both = [...a, ...b, 5];
console.log(both);
console.log(Math.max(...both));
function sum(...nums) {
return nums.reduce((t, n) => t + n, 0);
}
console.log(sum(1, 2, 3, 4));[ 1, 2, 3, 4, 5 ] 5 10
A quick copy
Spread is the easiest way to copy an array. Copy equals square brackets, dot dot dot, original. Changing the copy won't change the original. It's a shallow copy, which means arrays inside arrays are still shared. We'll talk about that more with objects.
| key | value |
|---|---|
| [...arr] | copy an array |
| [...a, ...b] | combine arrays |
| fn(...arr) | spread as arguments |
| function f(...args) | rest gathers |
Combining objects
Spread works on objects too. Here, default settings are combined with the user's choices. Later properties win, so the user's theme replaces the default. And rest in a function's parameters gathers any number of arguments into an array. Run it.
const defaults = { theme: "light", fontSize: 16, sound: true };
const choices = { theme: "dark" };
const settings = { ...defaults, ...choices };
console.log(settings);
function total(...prices) {
return prices.reduce((a, b) => a + b, 0);
}
console.log(total(2, 3), total(1, 2, 3, 4));{ theme: 'dark', fontSize: 16, sound: true }
5 10Summary
Spread unpacks arrays into values, and rest gathers values into an array. Next, destructuring, unpacking arrays into variables.
Key takeaways- ...spread
- ...rest
- [...arr] copies