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.
Subscribe to my newsletter
Read articles from Akash Thoriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Akash Thoriya
Akash Thoriya
As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.