JavaScript · The language round
What is the difference between spread and rest syntax?
Short answer
Spread expands an iterable or object into individual elements or properties. Rest collects multiple elements or properties into an array or object. They use the same ... token but do opposite jobs.
The syntax is identical, so the position tells you which one you are using. Spread appears where values are expected; rest appears where names are declared.
const parts = [2, 3];
const numbers = [1, ...parts, 4];
console.log(numbers); // [1, 2, 3, 4]
function sum(...values) {
return values.reduce((total, value) => total + value, 0);
}
console.log(sum(1, 2, 3)); // 6Objects
const defaults = { theme: "dark", size: "md" };
const overrides = { size: "lg" };
const config = { ...defaults, ...overrides };
console.log(config); // { theme: "dark", size: "lg" }
const { theme, ...rest } = config;
console.log(theme, rest); // "dark" { size: "lg" }- Spread in an array literal or function call expands values
- Spread in an object literal copies own enumerable properties
- Rest in a function parameter collects arguments into an array
- Rest in destructuring collects the remaining elements or properties
Both operations are shallow. Spreading an object copies references to nested objects, not the nested values themselves.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you tell spread and rest apart?
- 2Does object spread perform a deep clone?
- 3Can rest parameters replace the `arguments` object?
- 4What happens when two spread objects have the same key?
Say it in the interview
Spread expands a collection into individual values, such as array elements, function arguments, or object properties. Rest collects values into an array or object. They use the same three dots, but spread is used where values are expected and rest is used where a binding is declared. Both are shallow. For object spread, later properties overwrite earlier ones with the same key.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.