Spread and rest: three dots in both directions
Three dots do two jobs that are opposites, and the place they stand decides which one. In front of a value they spread it: the elements of an array or the properties of an object are written out where the dots are. In front of a name they rest: whatever is left over is collected into a new array or object under that name.
The distinction is worth holding on to, because the same three characters appear in a call, in a literal, in a parameter list and in a destructuring pattern. This lesson takes the four places one by one. It is the last lesson of the part, and the next part turns from values to text: numbers, strings and the formats that print them.
Spread in a call
A function that takes separate arguments cannot be given an array, because the array would arrive as one argument. Three dots in the call spread it: each element becomes an argument in its place, so Math.max(...scores) is Math.max(72, 95, 88).
const scores = [72, 95, 88];
console.log('max:', Math.max(...scores));
console.log('min:', Math.min(...scores));
console.log('lines:', ...scores);
console.log('sum:', scores.reduce((total, score) => total + score, 0));
node calls.mjs
max: 95
min: 72
lines: 72 95 88
sum: 255
The first two lines are the reason the syntax exists: Math.max reads its arguments, and the spread turned three array elements into three arguments. The third line spreads into console.log itself, which is why the numbers come out separated instead of bracketed.
Spread in an array
Inside an array literal the dots write the elements of another array in that place. The result is a new array, which makes the spread the shortest copy and also the shortest way to join two lists or to add an element at either end. A string spreads into its characters as well, because a string is iterable.
const first = [1, 2];
const second = [3, 4];
const combined = [...first, ...second, 5];
console.log(combined.join(', '));
const copy = [...first];
copy.push(99);
console.log('first:', first.join(', '));
console.log('copy:', copy.join(', '));
const letters = [...'abc'];
console.log(letters.join('|'));
node arrays.mjs
1, 2, 3, 4, 5
first: 1, 2
copy: 1, 2, 99
a|b|c
The combined array took the elements of both lists in the order the dots were written, and the copy stayed separate: the push reached the copy only. The last line is a string spread into characters, which is the same operation because the spread follows the iterator of the value.
Spread in an object
In an object literal the dots write the own enumerable properties of another object into the new one. The entries are written from left to right, so a later property with the same name wins, and a property written after the dots wins over both. The program below uses that order twice, once for a user setting that overrides a default and once for defaults that override a user.
const defaults = { theme: 'light', fontSize: 14 };
const user = { fontSize: 18 };
const settings = { ...defaults, ...user };
console.log(JSON.stringify(settings));
const override = { ...user, ...defaults };
console.log(JSON.stringify(override));
const extra = { ...defaults, fontFamily: 'serif' };
console.log(JSON.stringify(extra));
node objects.mjs
{"theme":"light","fontSize":18}
{"fontSize":14,"theme":"light"}
{"theme":"light","fontSize":14,"fontFamily":"serif"}
The first result kept the default theme and took the user font size, which is the usual shape of a merge. The second reversed the order and the default won, which is the bug the order prevents when it is written the wrong way round. The third shows a property added after the dots without any source object.
Rest parameters and patterns
A rest parameter collects the remaining arguments into a real array, so the body can loop over it, take its length or pass it on. In a destructuring pattern a rest element collects the elements or properties that were not named. The parameter must come last, and the element must come last too, because there would be no way to tell which value belongs to which name otherwise.
function total(label, ...values) {
let sum = 0;
for (const value of values) {
sum += value;
}
return `${label}: ${sum}`;
}
console.log(total('first', 1, 2, 3));
console.log(total('none'));
const [head, ...tail] = [10, 20, 30];
console.log('head:', head, 'tail:', tail.join(', '));
const { id, ...fields } = { id: 1, name: 'Ada', age: 36 };
console.log('id:', id);
console.log('fields:', Object.keys(fields).join(', '));
node rest.mjs
first: 6
none: 0
head: 10 tail: 20, 30
id: 1
fields: name, age
values is an array even when the call passes nothing, so the loop is safe and the empty call returns 0. The last two lines take one property out and leave the rest, which is how a record is split before an update without changing the original object. The rest element always builds a new array or object, so it copies one level and shares what is inside, like every other copy in this part.
Exercises
- Pass the scores of calls.mjs to a function of three parameters with a spread and print the three values. How many arguments arrive?
- Build an array with [...second, ...first] in arrays.mjs and print it. Which order do the elements have?
- Put fontSize: 12 between the two spreads in the first object of objects.mjs. Which value ends up in the result?
- Give total a second rest parameter and run the file. Which error arrives, and why is it a parse error?
- Spread an object into a call of Object.keys. What does the argument look like, and why is it not what the call expects?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Math.max(...scores)do whenscoresis an array of numbers?Answer
It passes each element as a separate argument
The spread writes the elements into the call, so a function of separate arguments gets them.
-
What does this program print?
console.log(Math.max(...[3, 7, 2]));Answer
7
The spread turns the three elements into three arguments, and the largest of them is 7.
-
What does this program print?
const a = [1, 2]; const b = [3]; console.log([...a, ...b].join("-"));Answer
1-2-3
Both arrays are spread into the new literal in order, and join writes the separator between the elements.
-
Which property wins in
{ ...defaults, ...user }when both objects havetheme?Answer
The one from user, because it is written later
The entries are written from left to right into the new object, so the later source overwrites the earlier one.
-
What does this program print?
const defaults = { theme: "light" }; const user = { theme: "dark" }; console.log({ ...defaults, ...user }.theme);Answer
dark
The user object comes after the defaults, so its theme is the value in the result.
-
What does this program print?
function count(...values) { return values.length; } console.log(count(1, 2, 3));Answer
3
The rest parameter collects all three arguments into an array, and its length is 3.
-
What does a rest parameter collect when the call passes no arguments at all?
Answer
An empty array
The rest parameter is always an array, so a call with nothing left over gives it zero elements.
-
Where may a rest element not stand in a pattern?
Answer
Anywhere but last
The rest takes everything that is left, so a name after it could never receive a value.
-
What does
const { id, ...fields } = record;copy intofields?Answer
Every property except id, in a new object
The named property is bound to id, and the rest element builds a new object from the other properties.
-
What does this program print?
const [head, ...tail] = [10, 20, 30]; console.log(head, tail.length);Answer
10 2
The first element goes to head, and the rest element holds the two that are left.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev