What’s the difference between rest and spread operators?
Deciphering Rest and Spread Operators in JavaScript
The rest and spread operators, both denoted by three dots (…), are versatile features in JavaScript that help manage arrays and objects more effectively. Despite their similar syntax, they serve different purposes and greatly enhance the language’s expressiveness and code conciseness. MDN documents both rest parameters and the spread syntax.
The Rest Operator
The rest operator allows the collection of an indefinite number of arguments into an array. It’s primarily used in function parameters to handle functions called with more arguments than formally specified. The rest operator simplifies the process of working with an unknown number of arguments, enabling dynamic function invocations.
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
The Spread Operator
Conversely, the spread operator allows an array or object to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. It’s commonly used for cloning or merging arrays and objects, making it a powerful tool for managing data structures without mutating the original sources. Note that these copies are... premium content.
