JavaScript Spread & Rest Operators
The spread operator `...` expands an array or object into individual elements, useful for copying, merging, or passing multiple arguments to a function.
The rest operator uses the same `...` syntax but works oppositely โ it gathers multiple values into a single array, commonly used in function parameters.
Spread
`[...arr1, ...arr2]` merges two arrays. `{...obj1, ...obj2}` merges two objects, with later properties overriding earlier ones.
Rest parameters
`function sum(...nums) { ... }` collects any number of arguments into a single array called nums.
let a = [1, 2];
let b = [3, 4];
let merged = [...a, ...b];
console.log(merged);[1, 2, 3, 4]Spread expands both arrays into a new combined array.
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4));10Rest parameters gather all arguments into a nums array.
Key points
- Spread (`...`) expands an iterable into individual elements.
- Rest (`...`) gathers multiple arguments into one array.
- Spread is great for copying and merging arrays/objects.
- Rest parameters must be the last parameter in a function.
