Spread & Rest Operators

The Spread and Rest operators both use the same syntax ... but serve different purposes in JavaScript.

Illustration of spread_rest_operators
Illustration of spread_rest_operators

💡 What is the Spread Operator?

The Spread operator expands an iterable (like an array or string) into individual elements.

Typical uses:

  • Copying or merging arrays
  • Passing array elements as function arguments
  • Expanding objects (ES2018+)

💡 What is the Rest Operator?

Rest collects multiple elements into a single array parameter. It is used in function parameters or destructuring assignments.

Typical uses:

  • Gathering remaining function arguments
  • Collecting leftover elements in destructuring
Spread vs Rest Syntax & Usage
OperatorPurpose
...arraySpread: Expands array elements
function(...args)Rest: Collects function arguments into an array
const [first, ...rest]Rest: Collects remaining elements during destructuring
{ ...obj }Spread: Copies object properties

📌 Deep Dive: Spread in Arrays

JAVASCRIPT
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
const combined = [...nums1, ...nums2];
console.log(combined);
Output
[1, 2, 3, 4, 5, 6]

📌 Deep Dive: Rest in Function Parameters

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

📌 Deep Dive: Rest in Array Destructuring

JAVASCRIPT
const [first, second, ...others] = [10, 20, 30, 40, 50];
console.log(first, second);  // 10 20
console.log(others);         // [30, 40, 50]
Output
10 20
[30, 40, 50]

📌 Deep Dive: Spread with Objects

JAVASCRIPT
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const mergedObj = {...obj1, ...obj2};
console.log(mergedObj);
Output
{a: 1, b: 2, c: 3, d: 4}

⚠️ Important Note

The Spread operator creates shallow copies. Nested objects or arrays inside copied arrays/objects still reference the original.

💡 Summary

  • ...array spreads elements
  • ...args in function gathers arguments into an array
  • Spread works on arrays and objects to expand or copy
  • Rest works in function parameters and destructuring to collect remaining elements