Skip to content
jshacks.dev
Fundamentals

Spread vs Rest Syntax in JavaScript Same Dots Different Jobs

Spread expands an iterable or object into separate items, and rest gathers items into one array or object. See each use, shallow copies and omitting keys.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Node.js and Vite logos.

The three dots are one token with two meanings, and the distinction is positional. Where a value is being used, they expand it into pieces. Where a name is being bound, they gather pieces into one value. A learner who sees ...args in a function signature and ...args in a call a line later is not looking at one feature twice, but at two features that happen to look the same. This post separates them, shows each use with output from Node.js 24, and covers the limits: the shallow copy, the iterable requirement for arrays, the order rules for objects and the large-array failure. The shallow copy is the subject of the post on shallow and deep copies, and the pattern syntax that rest uses is in the post on destructuring.

Spread: one thing becomes many

In an array literal, spread inserts each item of an iterable. In a call, it passes each item as an argument. In an object literal, it copies the own enumerable properties.

JavaScript
const head = [1, 2];
const tail = [5, 6];

console.log([...head, 3, 4, ...tail]);
console.log(Math.max(...[4, 9, 2]));
console.log([..."abc"]);
console.log([...new Set([1, 1, 2])]);
console.log([...new Map([["a", 1]])]);

const base = { host: "localhost", port: 80 };
console.log({ ...base, port: 8080, tls: true });
console.log({ port: 1, ...base });
Text
[ 1, 2, 3, 4, 5, 6 ]
9
[ 'a', 'b', 'c' ]
[ 1, 2 ]
[ [ 'a', 1 ] ]
{ host: 'localhost', port: 8080, tls: true }
{ port: 80, host: 'localhost' }

Spread works with any iterable: arrays, strings, sets, maps and generators. In the object forms, later entries win, so { ...base, port: 8080 } overrides the port and { port: 1, ...base } is overridden by it. That ordering is how defaults and overrides are written: the defaults first, the overrides last.

Spread needs an iterable, except in objects

An object is not iterable, so array spread and call spread throw on it. Object spread has no such requirement, and skips null and undefined quietly.

JavaScript
const plain = { a: 1 };

try {
  console.log([...plain]);
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log({ ...plain, ...null, ...undefined, ...false, ..."hi" });

try {
  console.log([...null]);
} catch (error) {
  console.log(error.name);
}

console.log({ ...[10, 20] });
Text
TypeError: plain is not iterable
{ '0': 'h', '1': 'i', a: 1 }
TypeError
{ '0': 10, '1': 20 }

Spreading a plain object into an array fails because it has no iterator. Spreading it into an object literal works. The null, undefined and false operands contributed nothing, and the string "hi" contributed its characters as indexed properties, because a string wraps into an object with those keys. Spreading an array into an object yields its index keys. These are legal and rarely what you mean, so treat them as accidents to catch.

Spread is a shallow copy

The new array or object holds the same nested references as the original. Changing a nested value shows through both.

JavaScript
const original = { id: 1, tags: ["a"], meta: { owner: "Ada" } };
const copy = { ...original };

copy.id = 2;
copy.tags.push("b");
copy.meta.owner = "Grace";

console.log(original);

const list = [{ n: 1 }];
const listCopy = [...list];
listCopy[0].n = 99;
console.log(list);
Text
{ id: 1, tags: [ 'a', 'b' ], meta: { owner: 'Grace' } }
[ { n: 99 } ]

The top-level id change stayed in the copy, and the nested tags and meta changes appeared in the original. This is the same reference rule as in the post on primitives versus objects, and it is the reason a "copy" made with spread can still corrupt shared state. Immutable updates copy only the path that changes: { ...state, meta: { ...state.meta, owner: "Grace" } }.

Rest in parameters

In a function signature, ...name gathers the remaining arguments into a real array. It replaces the arguments object, which is array-like and has no array methods.

JavaScript
function total(label, ...amounts) {
  return `${label}: ${amounts.reduce((sum, n) => sum + n, 0)}`;
}

console.log(total("none"));
console.log(total("sum", 5, 10, 20));

function legacy() {
  return Array.isArray(arguments);
}

const arrow = (...args) => Array.isArray(args);

console.log(legacy(), arrow());

try {
  eval("function bad(...rest, last) {}");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
none: 0
sum: 35
false true
SyntaxError: Rest parameter must be last formal parameter

The rest parameter receives every argument after the named ones, and an empty call gives an empty array, never undefined. It works in arrow functions, which have no arguments of their own. A rest parameter must be last, since it would otherwise swallow the arguments that later names expected, and the language rejects the other order at parse time.

Rest in destructuring

In a pattern, rest collects what was not matched, from an array or from an object.

JavaScript
const [first, second, ...others] = [1, 2, 3, 4, 5];
console.log(first, second, others);

const user = { id: 7, name: "Ada", password: "change-me", token: "abc" };
const { password, token, ...safe } = user;

console.log(safe);
console.log(Object.keys(user));
Text
1 2 [ 3, 4, 5 ]
{ id: 7, name: 'Ada' }
[ 'id', 'name', 'password', 'token' ]

Object rest is the standard way to leave keys out of a copy without mutating or using delete. The password and token variables exist and go unused, which some lint rules flag, and the ignoreRestSiblings option of no-unused-vars permits the pattern. The original object is unchanged.

Spread in calls and the size limit

Spreading an array into a call is convenient, and every item becomes a separate argument on the call stack. Very large arrays can exceed the engine's limit.

JavaScript
const big = Array.from({ length: 5_000_000 }, (_, i) => i);

try {
  console.log(Math.max(...big));
} catch (error) {
  console.log(error.name);
}

console.log(big.reduce((max, n) => (n > max ? n : max), -Infinity));
console.log([...big].length);
Text
RangeError
4999999
5000000

The call spread failed with a RangeError, while reduce and spread into a new array literal handled the same data. The exact limit depends on the engine and the stack size, and a few thousand items are safe everywhere. For arrays of unknown size, use a loop or reduce. The concat() post shows the same limit for push(...items).

Order, getters and symbols in object spread

Object spread copies own enumerable properties, including symbol keys, by reading them, so a getter is evaluated and its value stored.

JavaScript
const sym = Symbol("id");

const source = {
  a: 1,
  [sym]: "symbol",
  get computed() {
    console.log("getter ran");
    return 42;
  },
};

Object.defineProperty(source, "hidden", { value: 1, enumerable: false });

const copy = { ...source };

console.log(copy);
console.log(Object.getOwnPropertyDescriptor(copy, "computed"));
console.log("hidden" in copy);
Text
getter ran
{ a: 1, computed: 42, Symbol(id): 'symbol' }
{ value: 42, writable: true, enumerable: true, configurable: true }
false

The getter ran once, during the spread, and computed in the copy is a plain data property. The non-enumerable property was skipped, and the symbol key was copied. A faithful clone of an object with accessors needs descriptors, as covered in the post on property descriptors.

Everyday uses worth recognizing

A few idioms use these features so often that they are worth reading at a glance. Converting an array-like to an array: [...document.querySelectorAll("li")]. Combining arrays without mutation: [...a, ...b]. Adding an item immutably: [...list, item] and [item, ...list]. Removing by index without mutation: [...list.slice(0, i), ...list.slice(i + 1)]. Merging options: { ...defaults, ...options }. Forwarding arguments: (...args) => inner(...args). And passing a variable number of values to a function that takes fixed ones.

JavaScript
const defaults = { retries: 3, timeout: 100 };

function withDefaults(options = {}) {
  return { ...defaults, ...options };
}

function logCall(fn) {
  return (...args) => {
    console.log("calling with", args);
    return fn(...args);
  };
}

const add = logCall((a, b) => a + b);

console.log(withDefaults({ timeout: 250 }));
console.log(add(2, 3));
Text
{ retries: 3, timeout: 250 }
calling with [ 2, 3 ]
5

The wrapper accepts any number of arguments with rest and passes them on with spread, so it works for functions of any arity. This forward-everything shape is the basis of decorators, debounce helpers and middleware. The two uses of ... in one line read naturally once you know the rule: the first collects, the second expands.

A pair of reading rules

Reading spread and rest becomes automatic with two questions. Is this position a value or a binding? A call argument, an array element and an object entry are values, so ... expands. A parameter name and a destructuring target are bindings, so ... collects. And what is being iterated? Arrays and calls need an iterable, while objects need nothing.

Spread and TypeScript

TypeScript types spread and rest as you would expect: [...a, ...b] has the union of both element types, { ...base, ...overrides } has the merged property types with later ones replacing earlier, and a rest parameter has an array type such as ...args: number[]. Tuple rest, ...args: [string, ...number[]], types a fixed first argument followed by any number of others. These are checked at compile time, so a spread of the wrong shape is reported before it runs, which removes most of the accidental cases above.

Where spread and rest stop

Do not use spread to clone data you intend to edit deeply, since it is shallow. Do not spread large arrays into calls. Do not chain many spreads in a reducer over a big list, as in reduce((acc, x) => ({ ...acc, [x.id]: x }), {}), because each step copies the whole accumulator and the work grows with the square of the list. Mutate a local accumulator inside the reducer, or build with Object.fromEntries.

The syntax is defined in the specification under spread elements and rest parameters, and MDN's pages on spread syntax and rest parameters cover each.

Also inAPIs
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.