DEV Community

Arhan Khan
Arhan Khan

Posted on

Spread and Rest Operators in JavaScript: One Syntax, Two Jobs

The three dots ... in JavaScript do two completely different jobs depending on where you use them. When you spread, you unpack a collection. When you rest, you collect leftovers into one. Same syntax, opposite directions — and once you see the difference, you will use both everywhere.

Spread unpacks an array or object into individual pieces. It is the cleanest way to copy an array, merge objects, or pass array items as function arguments.

const nums = [1, 2, 3];
const more = [...nums, 4, 5]; // [1, 2, 3, 4, 5]

const user = { name: "Arhan", age: 22 };
const updated = { ...user, age: 23 }; // age updated, original untouched

console.log(Math.max(...nums)); // 3
Enter fullscreen mode Exit fullscreen mode

Rest does the reverse: it gathers remaining items into a single array or object. You see it most often in function parameters and destructuring.

function sum(first, ...rest) {
  return rest.reduce((total, n) => total + n, first);
}
sum(1, 2, 3, 4); // 10

const { name, ...details } = user;
console.log(details); // { age: 23 }
Enter fullscreen mode Exit fullscreen mode

The most common beginner mistake is thinking spread creates a deep copy. It does not — it is a shallow copy. Nested objects are still shared by reference, so changing a nested value in the copy changes the original too.

const original = { settings: { theme: "dark" } };
const copy = { ...original };
copy.settings.theme = "light";
console.log(original.settings.theme); // "light" — surprise!
Enter fullscreen mode Exit fullscreen mode

Use spread when you need a quick copy or merge, and rest when a function should accept any number of arguments. Together they replace a lot of old-style loops and Object.assign calls — and they make your code shorter without making it harder to read.

Top comments (0)