What is the spread operator?

The spread syntax (...) expands an iterable (array, string, Set, Map) into individual elements, or an object into its own properties, inside array literals, object literals and function calls.

Common uses

  • Copy an array: const copy = [...list].
  • Merge arrays: [...a, ...b].
  • Pass array items as arguments: Math.max(...numbers).
  • Copy or merge objects: { ...defaults, ...options }. Later properties win, which makes it perfect for "defaults + overrides".
  • Immutable updates: { ...state, user: { ...state.user, name: "Ada" } }, as used in React and Redux.
  • Convert iterables: [...new Set(list)] removes duplicates, [..."hello"] splits a string into characters (correctly handling emoji).

Important: spread is shallow

Spread copies only the top level. Nested objects are still shared, so changing copy.address.city also changes the original. For a deep copy use structuredClone.

Other details

  • Object spread copies own enumerable properties only, not the prototype or getters as getters (they are evaluated into values).
  • Spreading a huge array into a function call can exceed the argument limit; prefer reduce or a loop for very large inputs.
  • Spread vs rest: same ... syntax, opposite job. Spread expands, rest collects.

Code example

js
1const nums = [3, 9, 1];
2console.log(Math.max(...nums)); // 9
3
4const merged = [...nums, ...[7, 8]];
5console.log(merged); // [3, 9, 1, 7, 8]
6
7console.log([...new Set([1, 1, 2, 3, 3])]); // [1, 2, 3]
8console.log([..."héllo👋"]); // ["h", "é", "l", "l", "o", "👋"]
9
10const defaults = { theme: "light", fontSize: 14, beta: false };
11const userPrefs = { fontSize: 16 };
12console.log({ ...defaults, ...userPrefs }); // fontSize 16 wins
13
14// Immutable update of nested state
15const state = { user: { name: "Ada", address: { city: "London" } }, count: 1 };
16const next = { ...state, user: { ...state.user, name: "Grace" } };
17console.log(state.user.name, next.user.name); // Ada Grace
18
19// Spread is shallow!
20const shallow = { ...state };
21shallow.user.address.city = "Paris";
22console.log(state.user.address.city); // Paris - nested object was shared
23
24const deep = structuredClone(state);
25deep.user.address.city = "Rome";
26console.log(state.user.address.city); // still Paris

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app