What is the difference between the spread and rest operators?
Both are written as three dots. Rest collects many values into one array or object, in function parameters and destructuring. Spread expands one array or object into many items, in calls and literals.
Explain it simply
The same three dots do opposite jobs, depending on where they sit.
Rest packs. It appears on the left or in a parameter list, and gathers leftovers into one container: "the rest of the items go in this bag".
Spread unpacks. It appears on the right or in a call, and spills a container's items out: "empty this bag here".
With objects, spread also merges, and the last key wins. Remember spread makes a shallow copy.
Example
function sum(...nums) { // rest: packs arguments
return nums.reduce((a, n) => a + n, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
// spread: unpacks the array into separate arguments
console.log(Math.max(...[1, 5, 2])); // Output: 5
const [head, ...others] = [1, 2, 3];
console.log(others); // Output: [2,3]
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(rest); // Output: {"b":2,"c":3}
console.log({ ...{ a: 1, b: 2 }, ...{ b: 3 } }); // Output: {"a":1,"b":3}What to say in the interview
"Rest gathers remaining values into an array or object; it is used in function parameters and destructuring patterns, and must be last. Spread expands an iterable or object into individual items in calls and literals. In object spread, later properties override earlier ones."
Common mistakes
- Putting rest anywhere but last in a parameter list or pattern.
- Assuming spread deep copies nested values.