Spread vs Rest operators
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.
// 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:
// 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:
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
Advantages of this method:
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).