Spread & Rest Operators in JavaScript
JavaScript uses the same syntax (`...`) for both **spread** and **rest** operators, but they serve opposite purposes:
- Spread: Expands arrays or objects
- Rest: Collects remaining items into an array
๐งจ Spread Operator
Used to copy or expand iterable values like arrays or objects.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
const obj1 = { name: "Alice" };
const obj2 = { ...obj1, age: 30 };
console.log(obj2); // { name: "Alice", age: 30 }
๐ฅ Rest Operator
Used in function parameters or destructuring to group remaining values into an array.
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
๐งฉ Rest in Destructuring
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others); // { b: 2, c: 3 }
๐ Combining Spread with Functions
const numbers = [4, 5, 6];
console.log(Math.max(...numbers)); // 6
โ
Quick Recap:
...spread
โ expands values...rest
โ collects leftovers