Spread and Rest Operators
The spread and rest operators are both represented by three dots (...), but they have different functionalities.
Spread Operator
The spread operator allows you to expand an iterable (like an array or object) into individual elements.
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]
Rest Operator
The rest operator allows you to collect multiple elements into an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6