Spread and Rest Operators
Expert-Level Explanation
In ES6, the spread operator (...
) allows an iterable, such as an array, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. The rest operator (...
), while syntactically similar, is used to merge a list of function arguments into an array.
Creative Explanation
Imagine the spread operator as a deck of cards being spread out on a table, each card representing an array element laid out individually. The rest operator is like collecting individual cards (arguments) into a single stack (array).
Practical Explanation with Code
// Spread operator
let parts = ['shoulders', 'knees'];
let body = ['head', ...parts, 'toes']; // ['head', 'shoulders', 'knees', 'toes']
// Rest operator
function joinParts(...parts) {
console.log(parts); // ['head', 'shoulders', 'knees', 'toes']
}
joinParts('head', 'shoulders', 'knees', 'toes');
Real-world Example
Using the spread operator is like unpacking a suitcase into a wardrobe, where each item is placed individually. The rest operator is like packing a backpack, where various items are gathered together into one container.