Spread Operator (...
)
The spread operator allows an iterable (like an array or a string) to be expanded into individual elements. It can also be used to copy and merge objects.
Use Cases
-
Expanding Arrays:
- You can use the spread operator to expand an array into individual elements.
Example:
-
Combining Arrays:
- You can combine multiple arrays into one.
Example:
-
Copying Arrays:
- You can create a shallow copy of an array.
Example:
-
Expanding Objects:
- You can use the spread operator to expand an object into individual properties.
Example:
-
Combining Objects:
- You can combine multiple objects into one.
Example:
Rest Pattern (…)
The rest pattern allows you to represent an indefinite number of arguments as an array. It is often used in function parameters to handle multiple arguments.
Use Cases
-
Function Parameters:
- You can use the rest pattern to collect all remaining arguments into an array.
Example:
-
Array Destructuring:
- You can use the rest pattern to collect the remaining elements of an array after destructuring.
Example:
-
Object Destructuring:
- You can use the rest pattern to collect the remaining properties of an object after destructuring. Example:
Comparison
Aspect | Spread Operator | Rest Pattern |
---|---|---|
Syntax | ... before the iterable | ... before the parameter |
Purpose | Expands elements/properties | Collects elements/properties |
Use in Arrays | Expanding, copying, combining | Collecting the remaining elements after destructuring |
Use in Objects | Expanding, copying, combining | Collecting the remaining properties after destructuring |
Use in Function Arguments | Not applicable | Collecting multiple arguments into an array |
Concrete Examples
Individual Examples
1. Spread Operator Example: Combining Arrays
2. Rest Pattern Example: Function Arguments
3. Spread Operator Example: Expanding Objects
4. Rest Pattern Example: Object Destructuring
Examples where both the rest pattern and the spread operator are used
5. Combining Arrays and Collecting Remaining Elements
6. Copying and Merging Objects and Collecting Remaining Properties
7. Merging Arrays and Filtering Elements
8. Spreading into Function Arguments and Collecting Additional Arguments
9. Cloning and Updating Objects and Extracting Properties
Summary
- The spread operator (…) is used to expand elements of an iterable or properties of an object. It’s useful for copying, combining, and spreading arrays and objects.
- The rest pattern (…) is used to collect multiple elements into an array or remaining properties into an object. It’s commonly used in function parameters and destructuring.