Spread and Rest Operators in JavaScript: Differences and Examples
In JavaScript operators spread and rest use the ... syntax, but their purpose depends on the context in which they're used.
- Spread — unpacking operator that unpacks arrays or objects, allowing you to copy, combine and pass their elements.
- Rest — gathering operator that collects remaining elements into an array or object when you need to combine multiple values into one variable.
Spread Operator
Spread is used for:
Copying or combining arrays
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]
Copying or combining objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combined = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }
Passing array elements to function as separate arguments
function sum(a, b, c) {
return a + b + c;
}
const values = [1, 2, 3];
console.log(sum(...values)); // 6
Rest Operator
Rest is used for:
Collecting function arguments into array
function multiply(multiplier, ...numbers) {
return numbers.map(num => num * multiplier);
}
console.log(multiply(2, 1, 2, 3)); // [2, 4, 6]
Array destructuring
const [first, second, ...others] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(others); // [3, 4, 5]
Object destructuring
const { a, b, ...restProps } = { a: 10, b: 20, c: 30, d: 40 };
console.log(a); // 10
console.log(b); // 20
console.log(restProps); // { c: 30, d: 40 }
Spread vs Rest Differences
Syntax
Both operators use ..., but:
- Spread unpacks array values or object properties.
- Rest collects remaining elements or properties into array or object.
Usage
- Spread is used when calling functions, copying or combining arrays and objects.
- Rest is used in function parameters to collect arguments, and in destructuring to separate remaining elements.
Summary
- Spread allows "unpacking" arrays or objects, making copying and combining easier.
- Rest allows "collecting" multiple values into one array or object, convenient for passing variable number of arguments or destructuring.
These operators make code more flexible, concise and clear, helping efficiently manage data collections in JavaScript.