HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Spread and Rest

The triple-dot operator (...) is one of the most versatile tools in modern JavaScript. It serves two different purposes depending on how it's used: Spread and Rest.


1. The Spread Operator

The Spread operator allows an iterable (like an array or string) to be expanded into multiple elements. It is widely used for copying or merging data.

Spreading Arrays

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

const combined = [...arr1, ...[6, 7]]; // Merge arrays

Spreading Objects

const user = { name: "Mim", age: 22 };
const updatedUser = { ...user, city: "Dhaka" }; // Clone and add property

2. The Rest Parameter

The Rest parameter allows a function to accept an indefinite number of arguments as an array. It "collects" the remaining items.

Collecting Function Arguments

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

Rest in Destructuring

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

Rest vs. Spread (The Key Difference)

While the syntax is identical (...), their mental models are opposite:

  • Spread "expands" an array out into its elements.
  • Rest "collects" multiple elements in to an array.
Usage Tip: When using the Spread operator to clone an object or array, remember that it only performs a Shallow Copy. For nested objects, deeper cloning techniques may be required!

Key Points to Remember

  • Spread (...) expands iterables into separate elements
  • Rest (...) condenses many elements into a single array
  • The Rest parameter must be the last argument in a function definition
  • Spread is perfect for immutable state updates
  • Avoid using Spread for extremely large arrays as it can hit stack limits
  • It makes merging objects and arrays incredibly concise