← JavaScript

Intermediate · 11 of 17 · 15 min read

Spread and rest

The same three dots doing two opposite jobs, where each one is legal, and why the copy they make is only one level deep.

  • Spread & rest

... means two opposite things depending on where it appears. Spread expands something into its parts. Rest collects loose parts into one thing.

const parts = [1, 2, 3];

console.log(Math.max(...parts)); // spread: three arguments out of one array
const [first, ...others] = parts; // rest: two leftovers into one array
console.log(first, others);       // 1 [2, 3]

Spread with arrays

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

console.log([...a]);            // [1, 2] — a copy, not the same array
console.log([...a, ...b]);      // [1, 2, 3, 4] — merged
console.log([0, ...a, 99]);     // [0, 1, 2, 99] — anywhere in the literal
console.log([...'hi']);         // ["h", "i"] — strings are iterable
console.log([...new Set([1, 1, 2])]); // [1, 2] — the dedupe idiom

const copy = [...a];
copy.push(3);
console.log(a.length, copy.length); // 2 3 — independent at the top level

Spread works on anything iterable, which is what separates it from object spread:

console.log([...new Map([['a', 1]])]); // [["a", 1]]
console.log([...document?.querySelectorAll?.('div') ?? []]); // a real array from a NodeList

// console.log([...{ a: 1 }]); // TypeError: {} is not iterable

It is also the clean way to use an array method without mutating:

const nums = [3, 1, 2];
console.log([...nums].sort((x, y) => x - y)); // [1, 2, 3]
console.log(nums);                             // [3, 1, 2] — untouched
console.log([...nums].reverse());              // [2, 1, 3]

Spread with objects

Object spread copies own, enumerable properties. Later keys overwrite earlier ones, which is the whole mechanism behind defaults and updates:

const defaults = { theme: 'dark', fontSize: 14 };
const userPrefs = { fontSize: 16 };

console.log({ ...defaults, ...userPrefs }); // { theme: 'dark', fontSize: 16 }
console.log({ ...userPrefs, ...defaults }); // { theme: 'dark', fontSize: 14 } — defaults won

Order is the thing to get right: the last spread wins. Defaults go first, overrides go last.

const user = { id: 1, name: 'Ana', role: 'member' };

console.log({ ...user, role: 'admin' });   // override one field
console.log({ role: 'admin', ...user });   // role is back to 'member' — the spread was last

What object spread does not copy:

const source = {
  own: 1,
  get computed() { return 2; },
};
Object.defineProperty(source, 'hidden', { value: 3, enumerable: false });
const child = Object.create(source);
child.mine = 4;

const spread = { ...child };
console.log(spread);          // { mine: 4 } — nothing inherited, nothing non-enumerable
console.log({ ...source });   // { own: 1, computed: 2 } — the getter was *invoked*, not copied

That last line matters: spreading an object with a getter stores the value it returned at that moment. The result is a plain property, and the getter is gone.

Rest in parameters

Collects every remaining argument into a real array. It must be last, and there can be only one:

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

function log(level, ...parts) {
  return `[${level}] ${parts.join(' ')}`;
}
console.log(log('warn', 'disk', 'full')); // "[warn] disk full"

// function bad(...rest, last) {} // SyntaxError: must be the last parameter

Rest is the modern replacement for arguments, and it is better in three ways:

arguments ...rest
A real array no, array-like yes
Available in arrow functions no yes
Includes only the extras no, all of them yes
const arrow = (...args) => args.map((n) => n * 2);
console.log(arrow(1, 2)); // [2, 4]

function old() {
  // return arguments.map(…); // TypeError: not a function
  return Array.from(arguments).map((n) => n * 2);
}
console.log(old(1, 2)); // [2, 4]

Rest in destructuring

const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail); // 1 [2, 3, 4]

const { id, ...fields } = { id: 1, name: 'Ana', role: 'member' };
console.log(id, fields); // 1 { name: 'Ana', role: 'member' }

Object rest is the idiomatic way to remove a key without mutating — note that the discarded name still has to be bound to something:

const user = { id: 1, password: 'secret', name: 'Ana' };

const { password: _ignored, ...safe } = user;
console.log(safe); // { id: 1, name: 'Ana' }
console.log(user.password); // "secret" — the original is untouched

Rest in a pattern must also come last, and it takes no default:

const [a, ...rest] = [1, 2, 3];
// const [...head, last] = [1, 2, 3]; // SyntaxError
// const [...all = []] = [];          // SyntaxError
console.log(a, rest); // 1 [2, 3]

The copy is shallow

The most important practical fact about spread, and the source of most bugs attributed to it:

const original = { name: 'Ana', tags: ['a', 'b'], address: { city: 'Rosario' } };
const copy = { ...original };

copy.name = 'Beto';               // top level: independent
console.log(original.name);       // "Ana"

copy.tags.push('c');              // nested: the same array
console.log(original.tags);       // ["a", "b", "c"]
copy.address.city = 'Córdoba';
console.log(original.address.city); // "Córdoba"

Copy each level you intend to change:

const original = { tags: ['a'], address: { city: 'Rosario' } };

const safe = {
  ...original,
  tags: [...original.tags, 'b'],
  address: { ...original.address, city: 'Córdoba' },
};

console.log(original.tags, original.address.city); // ["a"] "Rosario"
console.log(safe.tags, safe.address.city);         // ["a", "b"] "Córdoba"

Or deep-copy the whole thing when the structure is big and genuinely tree-shaped:

const deep = structuredClone({ a: { b: { c: 1 } } });
deep.a.b.c = 2;
console.log(deep.a.b.c); // 2 — nothing shared

Where ... is not allowed

const arr = [1, 2];

// const [...a, b] = arr;        // SyntaxError: rest must be last
// function f(...a, b) {}        // SyntaxError
// const o = { ...1 };           // allowed, gives {} — primitives spread to nothing
console.log({ ...1 }, { ...'ab' }, { ...null }); // {} { '0': 'a', '1': 'b' } {}

Spreading null or undefined into an object is safe and contributes nothing, which makes conditional spreading a clean idiom:

const includeEmail = false;
const payload = {
  name: 'Ana',
  ...(includeEmail ? { email: 'a@b.c' } : null), // nothing added
};
console.log(payload); // { name: 'Ana' }

In an array literal the same trick needs an array, because null is not iterable:

const extra = false;
console.log([1, ...(extra ? [2] : [])]); // [1]
// console.log([1, ...(extra ? [2] : null)]); // TypeError: null is not iterable

Common mistakes

Spreading in a loop

Mistake. items.reduce((acc, x) => ({ ...acc, [x.id]: x }), {}). Why it fails. Every iteration copies the entire accumulator, so the work is O(n²) — slow enough to notice from a few thousand items. What to do instead. Mutate the accumulator you own and return it, or Object.fromEntries(items.map(…)).

Expecting a deep copy

Mistake. const draft = { ...state } and then writing to draft.list[0]. Why it fails. The nested array is shared, so the original changed too. What to do instead. Copy the nested level explicitly, or structuredClone.

Getting the merge order backwards

Mistake. { ...overrides, ...defaults }. Why it fails. The last spread wins, so the defaults overwrite the user’s choices. What to do instead. Defaults first, overrides last — and remember a key: value written after a spread also overrides it.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

Copying an object raises the question of how deep the copy goes.

What does this log?

Code sample
const a = { x: 1, nested: { y: 2 } };
const b = { ...a };
b.nested.y = 99;
console.log(a.nested.y);

A rest parameter and the named parameters before it divide the arguments between them.

What does this log?

Code sample
function sum(first, ...rest) {
  return rest.length;
}

console.log(sum(1, 2, 3, 4));

... appears both in a parameter list and in a function call. Does it mean the same thing?

Practise Spread & rest →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.