The JavaScript Spread ... operator
The spread operator ... expands an array, object or iterable into its individual elements. [...a, ...b] merges arrays; {...obj} copies an object; Math.max(...nums) passes array items as arguments. The same ... syntax in a function parameter is the rest operator, which gathers arguments into an array.
Overview
The spread operator, three dots, takes a collection and spreads it out into individual pieces. In an array literal, [...arr] drops in every element of arr; [...a, ...b] is a clean way to merge two arrays (the modern stand-in for concat()). With objects, {...obj} copies its properties, and {...defaults, ...overrides} merges them — overrides winning.
It's also how you turn an array back into separate arguments. Math.max() wants individual numbers, not an array, so Math.max(...nums) spreads the array into arguments. This combo — array in, spread to a function expecting separate values — is everywhere.
One source of confusion: the identical ... syntax means the opposite thing in a function's parameter list. There it's the rest operator: function sum(...nums) gathers all the arguments into an array. Same three dots, mirror-image jobs — spread expands, rest collects. Note that spread makes a shallow copy, so nested objects are still shared by reference.
Syntax
// spread (expand)
const merged = [...arr1, ...arr2];
const copy = { ...original };
Math.max(...numbers);
// rest (collect) - in a parameter list
function sum(...nums) { /* nums is an array */ }
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
const max = Math.max(...merged);
const copy = { ...{ x: 1 }, y: 2 };
document.getElementById('out').textContent =
'merged: ' + merged.join(', ') + '\n' +
'max: ' + max + '\n' +
'object: ' + JSON.stringify(copy);
</script>
Best practices
- Merge arrays with
[...a, ...b]and objects with{...a, ...b}— clean and non-mutating. - Copy with
[...arr]or{...obj}, remembering it's a shallow copy. - Spread an array into a function that wants separate arguments:
fn(...args). - Use
...restin parameters to collect a variable number of arguments into an array.
Frequently asked questions
What does the spread operator (...) do?
What is the difference between spread and rest?
... syntax, opposite jobs: spread expands a collection into pieces; rest gathers function arguments into an array. Rest appears in a parameter list.How do I copy an array or object with spread?
[...arr] for an array or {...obj} for an object. Both are shallow copies.How do I merge two arrays?
[...first, ...second] — the modern equivalent of concat().