What is the difference between spread and rest syntax?
Spread and rest use the same three dots, and they are two sides of the same idea. They both take a group of values apart and put them back together. The only difference is where the three dots appear. Spread appears where a value is expected, and it expands one thing into its individual parts. Rest appears where a parameter is expected, and it collects several arguments into one array.
const numbers = [1, 2, 3];
// Spread expands an array into individual values.
const copy = [...numbers];
console.log(copy); // [1, 2, 3]
console.log(copy === numbers); // false - a new array was created
// Rest collects several arguments into one array.
function sum(...values) {
let total = 0;
for (let index = 0; index < values.length; index++) {
total = total + values[index];
}
return total;
}
console.log(sum(1, 2, 3, 4)); // 10
// Spread also merges arrays.
const merged = [...numbers, 4, ...[5, 6]];
console.log(merged); // [1, 2, 3, 4, 5, 6]
A rest parameter has to be the last parameter in the list, because it collects everything that is left over. If you need to grab the first argument and then collect the rest, you write a normal parameter first and the rest parameter after it. That pattern shows up in middleware and in wrapper functions all the time.
Both of them also work on objects and not only on arrays. Spreading an object copies its own enumerable properties into a new object, and a rest element inside a destructuring pattern collects the properties that you did not name.
The mental model that helps in an interview is short. Spread is an expression that produces several values, and rest is a parameter that accepts several values. If you are on the right-hand side of an assignment or inside an argument list, then you are spreading. If you are inside a parameter list or a destructuring pattern, then you are resting.