You have two shopping lists: the array morning from the morning market and the array afternoon from the afternoon market. You want to join them. [morning, afternoon] looks right. But it gives an array that holds two arrays, not one long list. What you need is to open each list, then pour its items into a new list.
That is the job of the three dots ..., which have two opposite jobs. Spread unpacks the contents of an array or an object into separate pieces. Rest does the opposite: it gathers several values into one array. Which job the three dots do depends on where they are written.
Spread: unpack an array
In this code, the items of fruits are put in the middle of a new array:
const fruits = ["apple", "orange"];
const all = ["mango", ...fruits, "grape"];
console.log(all); // ["mango", "apple", "orange", "grape"]
console.log(all.length); // 4
...fruitsinside[ ]unpacks the items offruitsone by one, right at the place where the three dots are written.- Without the three dots,
["mango", fruits, "grape"]holds only 3 items. The second item is the wholefruitsarray, so the result is an array inside an array. fruitsitself doesn't change, because spread always makes a new array.
Two arrays are joined the same way: [...[1, 2], ...[3, 4]] gives [1, 2, 3, 4]. Text can be unpacked into its letters too: [..."code"] gives ["c", "o", "d", "e"].
Spread in objects: copy, then overwrite
In an object, spread copies properties into a new object:
const base = { name: "Budi", age: 17 };
const full = { ...base, major: "Science", age: 18 };
console.log(full); // { name: "Budi", age: 18, major: "Science" }
console.log(base.age); // 17
...basecopies each property ofbaseinto a new object.- Properties are filled in from left to right. When a key appears twice, the value written later is used. So
age: 18overwrites the17copied frombase. baseitself doesn't change.
Rest: gather the rest into an array
In a function's parameter list, the three dots do the opposite:
function total(first, ...rest) {
console.log(first); // 1
console.log(rest); // [2, 3, 4]
}
total(1, 2, 3, 4);
...restin the parameter list gathers every argument afterfirstinto one array.- When no arguments are left,
restis still an array, only an empty one:[]. - Rest has to be the last parameter.
Because rest is always an array, every array method works on it. In the function below, ...scores gathers all arguments into the scores array. Then reduce reduces them to one number: it starts from 0, and each turn adds n to total:
function average(...scores) {
const sum = scores.reduce((total, n) => total + n, 0);
return sum / scores.length;
}
console.log(average(80, 90, 100)); // 90
Rest is also used when you destructure an array: const [first, ...others] = [1, 2, 3, 4] puts 1 in first and [2, 3, 4] in others.
Spread or rest? Look at where it stands
- Where a value is used, the three dots unpack. That is spread. The places are: inside
[ ], inside{ }, or in the arguments of a function call, such asMath.max(...numbers), which finds the largest number in thenumbersarray. - Where a value is received, the three dots gather. That is rest. The places are: a function's parameters, or the left side of
=.
⚠️ When the three dots are missing or in the wrong place
- Forgetting the three dots when joining.
[a, b]makes an array that holds two arrays, for example[[1, 2], [3, 4]]. Write[...a, ...b]. - Rest that isn't the last parameter.
function f(...others, last)causes a SyntaxError. reducewithout a starting value.[].reduce((t, n) => t + n)causes a TypeError, because an empty array has no item to use as the starting value. Add, 0at the end.- A spread copy is shallow. Spread copies only the first layer. If a property holds an object or array, the copy and the original use the same one:
const original = { name: "Budi", address: { city: "Bristol" } };
const copy = { ...original };
copy.address.city = "Manchester";
console.log(original.address.city); // Manchester
const fullCopy = structuredClone(original);
fullCopy.address.city = "York";
console.log(original.address.city); // Manchester
copy.address and original.address are the same object, so changing the city through copy changes original too. structuredClone copies every layer, so changing fullCopy does not change original: the city stays the one set through copy.
TL;DR: ... (three dots) has two jobs. Where a value is used, ... is spread: it unpacks an array ([...a, ...b] joins two arrays), text ([..."code"]) or an object ({ ...base, age: 18 } copies base, and for a repeated key the later value wins). Where a value is received, ... is rest: it gathers the remaining arguments into one array (function f(first, ...rest)) and has to be the last parameter. Spread always makes a new array or object, so the original does not change.
⚡ Spread unpacks an array
Write:
const fruits = ["apple", "orange"];
const all = ["mango", ...fruits, "grape"];
// ["mango", "apple", "orange", "grape"]
Guess first: without the three dots, how many items does ["mango", fruits, "grape"] hold?
Three. The second item is the whole fruits array, so the result is an array inside an array.
Meaning: The three dots ... here are called spread. ...fruits unpacks the items of fruits one by one, right at that place. To join two arrays a and b, use [...a, ...b]. The original array doesn't change, because spread always makes a new array.
⚡ Objects: copy, then overwrite
Write:
const base = { name: "Budi", age: 17 };
const full = { ...base, major: "Science", age: 18 };
Meaning: ...base copies every property of base into a new object. Properties are filled in from left to right. When a key appears twice, the value written later is used: age becomes 18, while base.age stays 17.
⚡ Rest gathers the rest
Write:
function total(first, ...rest) {
console.log(rest); // [2, 3, 4]
}
total(1, 2, 3, 4);
Meaning: In the parameters, the three dots are called rest: they gather the remaining arguments into one array, and rest has to be the last parameter. The rule: inside [ ] or { }, where a value is used, ... unpacks (spread). In the parameters, where a value is received, ... gathers (rest).