TExcelTAD
Home › JavaScript › JS Spread & Rest

JavaScript Spread & Rest

Three dots ... mean two opposite things depending on where they appear:

  • Spread expands an iterable (or object) into individual elements — "unpack these".
  • Rest collects several elements into a single array (or object) — "pack the remainder".

A simple rule: on the right side of = or in a function call, it's spread. In a parameter list or on the left side of a destructuring =, it's rest.

Spread with arrays

js · try it yourself
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
const weekend = ["Sat", "Sun"];

const week = [...weekdays, ...weekend];
console.log(week);

const copy = [...weekdays];             // shallow copy
copy.push("Extra");
console.log(weekdays.length, copy.length);

console.log(["start", ...weekend, "end"]);
console.log([..."hey"]);                // any iterable works
console.log([...new Set([1, 1, 2])]);
[
  'Mon', 'Tue',
  'Wed', 'Thu',
  'Fri', 'Sat',
  'Sun'
]
5 6
[ 'start', 'Sat', 'Sun', 'end' ]
[ 'h', 'e', 'y' ]
[ 1, 2 ]

(Long arrays are printed over several lines by console.log, just like in Node.)

Spread in function calls

Spread turns an array into separate arguments:

js · try it yourself
const temps = [14, 22, 9, 17];
console.log(Math.max(...temps));
console.log(Math.min(...temps, 5));

function volume(l, w, h) {
  return l * w * h;
}
const box = [2, 3, 4];
console.log(volume(...box));
22
5
24

Spread with objects

Spreading an object copies its own properties into a new object literal. Later properties override earlier ones, which makes "copy with changes" easy:

js · try it yourself
const base = { host: "localhost", port: 3000, debug: false };
const dev = { ...base, debug: true };
const prod = { ...base, host: "example.com", port: 443 };

console.log(dev);
console.log(prod);
console.log(base);   // unchanged

const user = { name: "Ola", role: "user" };
const updated = { ...user, role: "admin", updatedBy: "system" };
console.log(updated);
{ host: 'localhost', port: 3000, debug: true }
{ host: 'example.com', port: 443, debug: false }
{ host: 'localhost', port: 3000, debug: false }
{ name: 'Ola', role: 'admin', updatedBy: 'system' }

Note: Spread makes a shallow copy. Nested objects and arrays are shared between the original and the copy. Use structuredClone() when you need a deep copy.

Rest parameters

In a function definition, ...name gathers all remaining arguments into a real array:

js · try it yourself
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3), sum(10), sum());

function tag(label, ...items) {
  return `${label}: ${items.join(", ")} (${items.length})`;
}
console.log(tag("Fruits", "fig", "kiwi", "lime"));
6 10 0
Fruits: fig, kiwi, lime (3)

A rest parameter must be the last parameter. It replaces the old arguments object, which isn't a real array and doesn't exist in arrow functions.

Rest in destructuring

js · try it yourself
const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail);

const { password, ...safeUser } = { id: 7, name: "Rui", password: "s3cret" };
console.log(safeUser);   // everything except the password
1 [ 2, 3, 4 ]
{ id: 7, name: 'Rui' }

Removing a property this way — without mutating the original object — is a very common pattern.

Summary

Where Name Example Effect
array literal spread [...a, ...b] combine / copy arrays
object literal spread { ...obj, x: 1 } copy / merge objects
function call spread fn(...args) array → arguments
parameter list rest function f(...args) arguments → array
array destructuring rest const [a, ...others] = arr remaining elements
object destructuring rest const { a, ...others } = obj remaining properties

Test yourself

What is [..."abc", "d"]?

  1. ["abc", "d"]
  2. ["a", "b", "c", "d"]
  3. "abcd"
  4. An error

What is { ...{ a: 1, b: 2 }, a: 9 }?

  1. { a: 1, b: 2 }
  2. { a: 9, b: 2 }
  3. { a: [1, 9], b: 2 }
  4. { a: 9 }

In function f(a, ...rest) {}, what is rest when calling f(1, 2, 3)?

  1. [1, 2, 3]
  2. [2, 3]
  3. 2
  4. 3