Spread vs Rest Operator in JavaScript: Key Differences and Usage
spread operator expands elements of an iterable (like arrays or objects) into individual elements, while the rest operator collects multiple elements into a single array or object. Both use the same syntax ..., but their roles differ based on context: spread unpacks, rest packs.Quick Comparison
Here is a quick side-by-side comparison of the spread and rest operators in JavaScript.
| Feature | Spread Operator | Rest Operator |
|---|---|---|
| Syntax | ... before iterable | ... before variable in function parameters or destructuring |
| Purpose | Expands elements of an iterable | Collects multiple elements into one array or object |
| Common Use Case | Copying or merging arrays/objects | Function parameters or destructuring assignment |
| Context | Used in array/object literals or function calls | Used in function parameters or destructuring patterns |
| Result Type | Individual elements spread out | Single array or object containing grouped elements |
Key Differences
The spread operator is used to unpack elements from arrays or properties from objects. For example, when you want to copy an array or merge objects, you use spread to expand their contents into a new array or object.
On the other hand, the rest operator collects multiple elements into a single array or object. It is commonly used in function parameters to gather all remaining arguments into one array, or in destructuring to group leftover properties.
Though both use the same ... syntax, their meaning depends on where they appear: spread appears in places where values are unpacked, while rest appears where values are packed together.
Code Comparison
Using the spread operator to merge two arrays:
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const merged = [...arr1, ...arr2]; console.log(merged);
Rest Operator Equivalent
Using the rest operator to collect function arguments into an array:
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4));
When to Use Which
Choose the spread operator when you want to expand or copy elements from arrays or objects, such as merging arrays or adding properties to objects.
Choose the rest operator when you want to gather multiple function arguments into one array or collect remaining elements during destructuring.
Remember, the same ... syntax does different jobs based on context: spreading unpacks, resting packs.
Key Takeaways
... but differ by context.