What is the difference between spread and rest syntax?
They use the same three dots and they are two sides of the same idea: taking a group of values apart and putting them back together. The difference is the position. Spread appears where a value is expected and expands something into its individual parts. Rest appears where a parameter is expected and collects several arguments into one array.
const numbers = [1, 2, 3];
// Spread: expand 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: collect several arguments into one array.
function sum(...values) {
return values.reduce((total, n) => total + n, 0);
}
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]Rest has to be the last parameter in a list, because it collects everything left over. If you need to grab the first argument and collect the rest, you write a normal parameter first and then the rest parameter, which is a common pattern for middleware and for variadic wrappers.
Both also work on objects, not just arrays. Spreading an object copies its own enumerable properties into a new object, and a rest parameter in a destructuring pattern collects the properties you did not name.
The mental model that helps in an interview is that spread is an expression that produces multiple values and rest is a parameter that accepts multiple values. If you are on the right-hand side of an assignment or inside an argument list, you are spreading. If you are in a parameter list or a destructuring pattern, you are resting.