Spread & Rest: The Three-Dot Trick

Spread & Rest: The Three-Dot Trick in JavaScript: The operator does two opposite jobs depending on where you put it: Spread unpacks a collection into…

Concept Explanation

The ... operator does two opposite jobs depending on where you put it:

  • Spread unpacks a collection into individual items — like emptying a bag onto a table.
  • Rest gathers leftover items into one array — like sweeping them back into the bag.

Same three dots, mirror-image behaviour. Spread is for expanding; rest is for collecting.


Syntax or Core Structure

Spread: copy and combine

const a = [1, 2];
const b = [3, 4];
const both = [...a, ...b];            // [1, 2, 3, 4]

const user = { name: "Al", age: 30 };
const updated = { ...user, age: 31 }; // copy, then override one key

Rest: collect the leftovers

function sum(...numbers) {            // any number of args -> array
  return numbers.reduce((t, n) => t + n, 0);
}
sum(1, 2, 3, 4); // 10

const [first, ...others] = [10, 20, 30]; // first = 10, others = [20, 30]

Real World Example

React state updates lean on spread every day: setUser({ ...user, verified: true }) builds a new object with one field changed instead of mutating the old one. Immutable updates like this are exactly what let frameworks detect changes and re-render correctly.


Common Mistakes

  1. Shallow copy only: { ...obj } copies the top level only. Nested objects are still shared references, not deep copies.
  2. Rest must be last: function f(...rest, last) is a syntax error. The rest parameter has to sit at the end.
  3. Spreading non-iterables: [...123] throws. You can spread arrays, strings, and Sets — not plain numbers.

Best Practices

  • Update immutably: build a new array or object with spread instead of push/direct assignment when state must not mutate.
  • Merge with intent: in { ...a, ...b }, later keys win — put your overrides last on purpose.
  • Clone before sorting: [...arr].sort() sorts a copy, protecting the original from .sort()'s in-place change.

Practice Exercises

  1. The Merger: Combine two arrays of names and remove duplicates using spread and a Set.
  2. The Updater: Given a settings object, return a new object with darkMode flipped, without mutating the original.
  3. The Max: Use Math.max(...numbers) to find the largest value in an array of numbers.