Rest Parameters and Spread Syntax in JavaScript
JavaScript provides Rest Parameters (...
) and Spread Syntax (...
) to handle variable numbers of arguments and spread arrays/objects into individual elements.
Rest Parameters (...
)
Rest parameters allow a function to accept any number of arguments and store them in an array.
Example: Function with Rest Parameters
How it works?
- The
...numbers
collects all arguments into an array. - We use
reduce()
to sum the values.
Rest Parameters with Other Arguments
Rules for Rest Parameters:
✔ Must be the last parameter in the function.
✔ Only one rest parameter is allowed per function.
Spread Syntax (...
)
The spread operator (...
) expands iterable objects (arrays, strings, objects, etc.) into individual elements.
Example: Spreading an Array into Arguments
How it works?
Math.max()
normally expects separate arguments....numbers
spreads the array elements into separate arguments.
Combining Arrays
✔ Spread syntax makes it easy to merge arrays!
Copying Arrays (Avoid Mutating Original)
✔ Unlike arr2 = arr1
(which creates a reference), [...]
creates a new copy.
Spreading Objects (...
)
We can spread object properties into a new object.
Cloning an Object
Merging Objects
Overriding Properties
✔ The last spread property takes precedence.
šÆ Summary
✔ Rest Parameters (...
) collect multiple arguments into an array.
✔ Spread Syntax (...
) expands arrays/objects into individual elements.
✔ Use cases:
- Rest parameters: Handle dynamic function arguments.
- Spread: Clone, merge, and expand arrays/objects.
š These features make JavaScript code more concise and flexible! Let me know if you need more examples. š