0
0
JavascriptComparisonBeginner · 4 min read

Spread vs Rest Operator in JavaScript: Key Differences and Usage

The 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.

FeatureSpread OperatorRest Operator
Syntax... before iterable... before variable in function parameters or destructuring
PurposeExpands elements of an iterableCollects multiple elements into one array or object
Common Use CaseCopying or merging arrays/objectsFunction parameters or destructuring assignment
ContextUsed in array/object literals or function callsUsed in function parameters or destructuring patterns
Result TypeIndividual elements spread outSingle 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:

javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2];
console.log(merged);
Output
[1, 2, 3, 4, 5, 6]
↔️

Rest Operator Equivalent

Using the rest operator to collect function arguments into an array:

javascript
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));
Output
10
🎯

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

The spread operator expands elements; the rest operator collects elements.
Both use the same syntax ... but differ by context.
Use spread to copy or merge arrays/objects.
Use rest to gather function arguments or remaining elements.
Understanding context is key to using these operators correctly.