Spread vs Rest Operators – How and When to Use Them
In JavaScript, both Spread and Rest operators use the same syntax (`...`), but serve different purposes. They were introduced in ES6 and are widely used when working with objects and arrays.
By understanding when to use Spread versus Rest, your code will become cleaner, more flexible, and readable.
Spread Operator – Expanding Values
// Spreading an array
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]
// Spreading an object
const user = { name: 'Ani', age: 25 };
const updatedUser = { ...user, age: 26 };
console.log(updatedUser); // { name: 'Ani', age: 26 }
Advantages of this method:
- Helps create new arrays or objects without mutating the original
- Works as a shallow copy – ideal for immutable approaches
Rest Operator – Collecting Values
// Using rest in array destructuring
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]
// Using rest with objects
const { name, ...restProps } = { name: 'Ani', age: 25, city: 'Yerevan' };
console.log(restProps); // { age: 25, city: 'Yerevan' }
Advantages of this method:
- Helps separate specific values while collecting the rest
- Useful when passing dynamic parameters
Rest in Function Parameters
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
Advantages of this method:
- Allows writing functions that accept unlimited arguments
- Creates an array-like list from any parameters
Comparison: When to Use Each
Spread (`...`) ➤ Use when you want to "expand" values into arrays or objects (e.g., copying, merging, expanding).
Rest (`...`) ➤ Use when you want to "collect" values into an array or object (e.g., during destructuring or in function parameters).