JavaScript’s three-dot syntax '...' is like a magical wand—but did you know it has two different powers? Enter the spread operator and the rest parameter. Both use the same syntax, yet serve opposite purposes. Understanding these can boost your coding skills and impress interviewers!
What is the Spread Operator?
The spread operator expands elements of an iterable (like array or object) into individual elements.
Example: Expanding arrays into function arguments or merging arrays.
What is the Rest Parameter?
The rest parameter collects multiple function arguments into a single array.
Example: Capturing all extra arguments as an array.
Common Real-Life examples of Spread and Rest in JavaScript
Here are some common real-life examples of the spread operator and rest parameter in JavaScript:
Spread Operator Examples
1- Merging Arrays
2- Copying Arrays3- Combining/Updating Objects (e.g., in React state updates)
4- Passing Array Elements as Function Arguments
Rest Parameter Examples
1- Functions Accepting Variable Number of Arguments
2- Destructuring Arrays with Rest
3- Gathering Object Properties
These examples illustrate how spread helps expand elements and rest helps gather elements flexibly in everyday coding scenarios, improving readability and functionality.
When to Use Each?
- Use spread when you want to expand an array or object into individual elements or combine multiple arrays/objects.
- Use rest when you want your function to accept an unknown number of arguments and handle them as an array.
Developer Scenario:
Imagine building a product list where you want to:
- Add new products to an existing array (spread helps with merging).
- Create a function to apply discounts to any number of products passed dynamically (rest helps capturing arbitrary parameters).
Difference between Spread Operator and Rest Parameter
| Feature | Spread Operator | Rest Parameter |
|---|---|---|
| Purpose | Expands elements of arrays or objects | Collects multiple function arguments into an array |
| Usage Location | In function calls, array and object literals | In function parameter lists |
| Functionality | Spreads out iterable elements | Gathers remaining arguments into an array |
| Example |
const arr = [1, 2]; const newArr = [...arr, 3, 4]; // [1, 2, 3, 4] |
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
|
| Common Use Case | Merging arrays or objects, function argument expansion | Functions with variable number of arguments |
Conclusion
Though both share the '...' syntax, the spread operator and rest parameter serve opposite roles—spreading out vs collecting in. Mastering these helps write flexible, readable, and elegant JavaScript code.