Skip to content
Velloreth
Programming 8 min read

The JavaScript Spread Operator: Uses and Traps

Spread expands an iterable into individual elements. Learn the copy, merge, and call patterns, plus the shallow-copy trap.

By

What spread does

Spread expands an iterable into individual elements.

const arr = [1, 2, 3];
console.log(...arr); // 1 2 3

It works in three places: array literals, function calls, and object literals.

Copying arrays

const original = [1, 2, 3];
const copy = [...original];

This is a shallow copy. For an array of primitives, it is a true copy. For an array of objects, the objects are shared.

const users = [{ name: 'Ada' }];
const copy = [...users];
copy[0].name = 'Grace';
console.log(users[0].name); // 'Grace' — shared object

Concatenating arrays

const combined = [...a, ...b];
const withExtra = [...a, 'x', ...b];

This replaces concat and is more flexible, because you can interleave values.

Spreading into function calls

const numbers = [5, 2, 9, 1];
Math.max(...numbers); // 9

Math.max takes individual arguments, so spread is required. The old way was Math.max.apply(null, numbers).

function log(level, message, ...rest) {
  console.log(level, message, rest);
}

const args = ['info', 'started', 'extra'];
log(...args);

Copying and merging objects

const copy = { ...original };
const merged = { ...defaults, ...overrides };

Later properties win, which makes the merge order meaningful.

const config = {
  ...defaultConfig,
  ...userConfig,
  // explicit overrides last
  version: '2.0',
};

The merge is shallow. A nested object in userConfig replaces the whole nested object in defaultConfig.

const defaults = { db: { host: 'localhost', port: 5432 } };
const user = { db: { host: 'remote' } };

const config = { ...defaults, ...user };
// { db: { host: 'remote' } } — port is lost

For a deep merge, you need a library or a recursive function.

Immutable updates

Spread is the standard way to update an object or array without mutating it.

// Update one property
const updated = { ...user, name: 'Grace' };

// Add a property
const withRole = { ...user, role: 'admin' };

// Remove a property
const { password, ...safe } = user;

// Append to an array
const appended = [...items, newItem];

// Update an array element
const changed = items.map((item, i) => (i === 2 ? { ...item, done: true } : item));

This pattern is central to React state updates and to any code that treats data as immutable.

Spreading strings

[...'hello']; // ['h', 'e', 'l', 'l', 'o']

Unlike split(''), spread respects code points, so it does not split surrogate pairs.

'👋'.split('');  // ['\uD83D', '\uDC4B'] — broken
[...'👋'];       // ['👋'] — correct

This makes spread the safer way to iterate characters.

Spreading Maps and Sets

const set = new Set([1, 2, 3]);
const arr = [...set]; // [1, 2, 3]

const map = new Map([['a', 1], ['b', 2]]);
const entries = [...map]; // [['a', 1], ['b', 2]]
const keys = [...map.keys()];
const values = [...map.values()];

This is the standard way to convert a Set to an array, and to deduplicate.

const unique = [...new Set([1, 2, 2, 3, 3])]; // [1, 2, 3]

Spread versus rest

The same ... syntax serves both, in opposite directions.

// Spread: expands
const arr = [...items];
fn(...args);
const obj = { ...source };

// Rest: collects
const [first, ...rest] = arr;
function fn(a, ...others) { }
const { id, ...others } = obj;

The rule: spread appears where values are expected, rest appears where a collection is being built.

Gotchas

Shallow copy

The most important one. Spread copies one level.

const state = { user: { name: 'Ada' }, items: [1, 2] };
const next = { ...state };

next.user.name = 'Grace'; // mutates the original
next.items.push(3);       // mutates the original

To update nested data immutably, spread at each level.

const next = {
  ...state,
  user: { ...state.user, name: 'Grace' },
  items: [...state.items, 3],
};

Spreading non-iterables

[...123];        // TypeError: 123 is not iterable
[...null];       // TypeError
[...undefined];  // TypeError

Objects are not iterable, so [...obj] throws. Use { ...obj } for objects.

Spreading into an object from an array

{ ...[1, 2, 3] } // { '0': 1, '1': 2, '2': 3 }

The array indices become keys. This is rarely what you want.

Performance with large arrays

const big = [...hugeArray]; // allocates a new array

For very large arrays in hot paths, spread allocates. slice() is comparable; a loop that avoids the copy is faster. For typical sizes it does not matter.

Spread in a function call has an argument limit

Math.max(...veryLargeArray); // RangeError: Maximum call stack size exceeded

The engine has a limit on the number of arguments. For very large arrays, use reduce.

veryLargeArray.reduce((max, n) => Math.max(max, n), -Infinity);

Spread does not copy non-enumerable properties

class User {
  constructor() { this.name = 'Ada'; }
  greet() { return 'hi'; } // on the prototype, not copied
}

const u = new User();
const copy = { ...u }; // { name: 'Ada' } — greet is lost

Spread copies own enumerable properties only. Prototype methods and non-enumerable properties are not included.

Spread versus alternatives

Spread is not always the right tool. Knowing the alternatives helps.

For copying an array, slice() is equivalent and slightly more explicit about intent.

const copy = arr.slice();
const copy2 = [...arr];

For concatenating, concat handles the same cases and is sometimes clearer when both operands are arrays.

const combined = a.concat(b);
const combined2 = [...a, ...b];

For merging objects, Object.assign mutates a target, which is occasionally what you want.

Object.assign(target, source); // mutates target
const merged = { ...target, ...source }; // new object

For a deep copy, spread is wrong. Use structuredClone.

const deep = structuredClone(original);

The pattern: spread is the modern default for shallow copies and merges, and the alternatives are worth knowing for the cases where they are clearer or where mutation is intended.

Spread in React and similar frameworks

Spread is central to immutable state updates, which is why it appears everywhere in React code.

// Update one field
setUser((prev) => ({ ...prev, name: 'Grace' }));

// Add to a list
setItems((prev) => [...prev, newItem]);

// Remove from a list
setItems((prev) => prev.filter((i) => i.id !== id));

// Update a nested field
setUser((prev) => ({
  ...prev,
  address: { ...prev.address, city: 'London' },
}));

The nested update is where the shallow-copy trap bites. Each level needs its own spread, and forgetting one mutates the original state, which React may not detect.

A common bug:

// Bug: mutates the nested object
setUser((prev) => {
  prev.address.city = 'London';
  return { ...prev };
});

The spread at the top level creates a new object, but address is the same reference, so the mutation is visible to the previous state. React’s comparison may not notice, and the component may not re-render.

Spread and the rest of the language

Spread composes with other features in ways that are worth recognising.

With destructuring. The rest pattern collects what spread would expand.

const [first, ...others] = arr;
const { id, ...rest } = obj;

With optional chaining. Spread does not guard against undefined, so combine them.

const merged = { ...defaults, ...(userConfig ?? {}) };

With default parameters. A rest parameter collects the remaining arguments.

function log(level, ...messages) { }

With array methods. Spread converts an iterable to an array, which unlocks the array methods.

[...new Set(items)].map((x) => x.id);

With function composition. Spreading an array of arguments into a call is the standard way to forward arguments.

function wrapper(...args) {
  return original(...args);
}

A note on readability

Spread is concise, and concision is not always clarity. A line with three spreads and an override is harder to read than three assignments, even though it is shorter. The judgement is whether a reader can tell at a glance what the result contains. When the answer is yes, spread is the right tool. When the reader has to trace the order of the spreads to work out which value wins, the explicit form is better. This is the same trade-off as any dense syntax: it pays off when the pattern is familiar, and it costs when the reader has to decode it.

Practical guidance

  • Use spread to copy and merge arrays and objects.
  • Remember it is a shallow copy — spread at each level for nested updates.
  • Use spread for immutable updates in React and similar code.
  • Use [...new Set(arr)] to deduplicate.
  • Use spread for Math.max and similar variadic functions.
  • Use spread on strings to respect code points.
  • Watch the argument limit for very large arrays.
  • Use structuredClone when you need a deep copy.

For the related guides, see javascript-destructuring-guide and javascript-array-methods-guide. For the broader context, immutability-explained and javascript-object-methods-guide.

Quotable summary

The spread operator expands an iterable into individual elements, and it works in array literals, function calls, and object literals. It performs a shallow copy, so nested objects and arrays are still shared with the original, which is the most important trap. Spread in an object literal copies own enumerable properties, making it the standard way to merge and override, with later properties winning. The rest pattern is the inverse, collecting values into an array or object, and it appears in destructuring and function parameters. Spreading a string produces an array of characters and respects code points, unlike split(”), and spreading into Math.max works because the function takes individual arguments rather than an array.

Frequently asked questions

What does the spread operator do?
It expands an iterable — an array, string, Map, or Set — into individual elements. In an array literal it copies elements, in a function call it passes them as arguments, and in an object literal it copies properties.
Is spread a deep copy?
No. Spread is a shallow copy, so nested objects and arrays are shared with the original. Use structuredClone for a deep copy.
What is the difference between spread and rest?
They use the same syntax but opposite directions. Spread expands a collection into individual values. Rest collects individual values into a collection, and it appears in destructuring or function parameters.
How do I merge two objects?
Use spread in an object literal: const merged = { ...a, ...b }. Later properties win, so b overrides a on conflicts. The merge is shallow.
Can I spread a string?
Yes. [...'hello'] produces ['h', 'e', 'l', 'l', 'o']. Unlike split(''), spread respects code points, so emoji are not split into halves.
Why does spreading an array into Math.max work?
Because Math.max takes individual arguments, not an array. Math.max(...numbers) spreads the array into separate arguments. Without spread you would need Math.max.apply(null, numbers).