JavaScript Spread Operator Explained: Spread vs Rest, Copies and Gotchas, Tested
The JavaScript spread operator, three dots before a value, expands arrays, strings and objects into individual items. Learn how it copies and merges data, how it differs from rest parameters, and where it breaks, with output we ran on Node 24.
- The JavaScript spread operator (
...) expands an iterable or object into separate values; rest does the opposite and collects values. - Spread makes shallow copies: changing a nested object in the copy also changed the original in our test.
- On Node 24,
Math.max(...arr)worked with 100,000 items but threwRangeErrorat 200,000. - Spreading the accumulator inside
reducetook 51.7 ms for 5,000 items, against 0.84 ms for a simple loop.
Three dots have become one of the most common sights in modern JavaScript. You see them in React state updates, API helpers, config merging and function signatures. The JavaScript spread operator is short and expressive, but it hides a few traps: copies that are not really copies, a hard limit on function arguments and a hidden quadratic cost.
We ran every snippet below on Node.js v24.22.1 and copied the output. Browsers follow the same language rules, though exact limits such as the maximum argument count can differ by engine. If you are new to the syntax family, our JavaScript destructuring guide covers the closely related pattern syntax, and our JavaScript tutorial for beginners covers the basics.
What is the spread operator?
Spread syntax, written ...value, takes something that holds many items and expands it in place. It works in three positions:
- Array literals:
[...a, ...b]builds a new array from other iterables. - Function calls:
fn(...args)passes array items as separate arguments. - Object literals:
{...obj}copies an object’s own enumerable properties.
Strictly speaking, it is syntax rather than an operator, because it cannot be used on its own like +. Everyone still calls it the spread operator, and so will we.
Spreading arrays
Merging and copying arrays is the most common use:
const a = [1, 2], b = [3, 4];
console.log([...a, ...b, 5]); // [ 1, 2, 3, 4, 5 ]
const copy = [...a];
copy.push(99);
console.log(a, copy); // [ 1, 2 ] [ 1, 2, 99 ]
console.log(Math.max(...[4, 9, 2])); // 9
console.log(Math.max(...[])); // -Infinity
The copy is a new array, so pushing to it leaves a alone. Spreading into a function call is the modern replacement for Math.max.apply(null, arr). Note the empty case: Math.max() with no arguments returns -Infinity, which can slip into reports unnoticed. For other ways to transform arrays, see our JavaScript array methods guide.
Shallow copies: the most common bug
Spread copies one level deep. Nested objects are shared by reference between the original and the copy:
const nested = [{ n: 1 }];
const sh = [...nested];
sh[0].n = 42;
console.log(nested[0].n); // 42 (original changed!)
const orig = [{ n: 1 }];
const d2 = structuredClone(orig);
d2[0].n = 7;
console.log(orig[0].n); // 1 (original safe)
This is the root of many “state changed by itself” bugs in front-end code. When you need a full independent copy of plain data, use structuredClone, which is built into Node and modern browsers. When you update nested state, spread at every level you change, for example {...user, address: {...user.address, city: "Pune"}}.
Strings, Sets and Maps
Array spread works on anything iterable, not just arrays:
console.log([..."héllo"]); // [ 'h', 'é', 'l', 'l', 'o' ]
console.log([..."👍🏽ok"].length, "👍🏽ok".split("").length); // 4 6
console.log([...new Set([3, 1, 3, 2, 1])]); // [ 3, 1, 2 ]
console.log([...new Map([["a", 1], ["b", 2]])]); // [ [ 'a', 1 ], [ 'b', 2 ] ]
The emoji line is worth a second look. Spreading a string splits it by Unicode code points, while split("") splits by UTF-16 code units, so the same string gave 4 items one way and 6 the other. Spread is the safer choice for counting characters, though a skin-tone emoji is still two code points. Spreading a Set is the shortest way to remove duplicates, and spreading a Map gives its entries. Our Map vs Object guide explains when to choose each.
Spreading objects
Object spread copies own enumerable properties into a new object. When keys collide, the one written later wins:
const base = { theme: "light", lang: "en" };
console.log({ ...base, lang: "fr" }); // { theme: 'light', lang: 'fr' }
console.log({ lang: "fr", ...base }); // { lang: 'en', theme: 'light' }
console.log({ ...null, ...undefined, x: 1 }); // { x: 1 }
class P { constructor() { this.own = 1 } get g() { return 2 } }
P.prototype.proto = 3;
console.log({ ...new P() }); // { own: 1 }
Order matters: put defaults first and overrides last. Spreading null or undefined into an object is silently ignored, which makes optional config easy. But only own properties are copied, so getters and prototype properties from a class instance disappear, and the result is a plain object, not a P. Never use object spread to clone class instances.
Spread vs rest parameters
The same three dots also mean rest, which collects values instead of expanding them. The position tells you which one you are looking at:
function sum(...nums) { // rest: collects arguments
return nums.reduce((s, n) => s + n, 0);
}
console.log(sum(1, 2, 3), sum()); // 6 0
const [first, ...others] = [10, 20, 30];
console.log(first, others); // 10 [ 20, 30 ]
const { password, ...safe } = { id: 7, name: "Demo", password: "x" };
console.log(safe); // { id: 7, name: 'Demo' }
| Question | Spread | Rest |
|---|---|---|
| What it does | Expands one value into many | Collects many values into one |
| Where it appears | Calls, array and object literals | Function parameters, destructuring |
| How many allowed | Any number | One, and it must be last |
| Result type | Separate values or a new literal | A real array or a plain object |
Rest parameters produce a true array, so Array.isArray returned true in our test, while the old arguments object returned false. Also, rest parameters are not counted in a function’s length: ((a, b, ...c) => 0).length printed 2. The object-rest pattern above is a tidy way to strip secrets such as a password before logging or sending data.
The argument limit nobody mentions
Spreading into a function call passes every item as a separate argument, and engines limit how many arguments one call can have. We tested Math.max(...arr) with growing arrays:
| Array length | Result on Node 24.22.1 |
|---|---|
| 100,000 | Worked |
| 200,000 | RangeError: Maximum call stack size exceeded |
| 1,000,000 | RangeError |
| 10,000,000 | RangeError |
A reduce loop handled 10 million items without trouble. If an array can be large, such as rows from a database or a CSV upload, avoid spreading it into a call. The same applies to arr.push(...other): pushing a 200,000-item spread also threw RangeError in our test.
A performance trap: spread inside reduce
A popular one-liner builds a lookup object by spreading the accumulator on every step. It looks clean, but each step copies everything built so far:
// Copies the whole object on every iteration
items.reduce((acc, it) => ({ ...acc, [it.id]: it }), {});
// Mutates one object in place
const o = {};
for (const it of items) o[it.id] = it;
With 5,000 items, the spread version took 51.7 ms and the loop took 0.84 ms in our run, around 60 times slower. The gap grows quadratically with size. Immutability is valuable for shared state, but inside a function that owns its accumulator, plain mutation is safe and fast. Object.fromEntries(items.map(it => [it.id, it])) is a readable alternative; it took 1.78 ms for the same 5,000 items in our run.
Errors you will see
TypeError: null is not iterable: array spread onnullorundefined. Use[...(list ?? [])].TypeError: ... is not iterable: spreading a plain object into an array. UseObject.values(obj)orObject.entries(obj)first.RangeError: Maximum call stack size exceeded: too many items spread into a function call.- Silent shared state: not an error at all, which is why the shallow copy bug survives code review. Test that edits to a copy leave the original unchanged.
JavaScript spread operator cheat sheet
| Task | Code |
|---|---|
| Merge arrays | [...a, ...b] |
| Copy an array (shallow) | [...a] |
| Remove duplicates | [...new Set(a)] |
| Merge objects, last wins | {...defaults, ...overrides} |
| Remove a key | const {key, ...rest} = obj |
| Deep copy plain data | structuredClone(obj) |
| Variable arguments | function f(...args) {} |
Final thoughts
The JavaScript spread operator makes code shorter and intent clearer, as long as you remember what it does under the hood. It copies one level only, it passes every item as a separate argument, and it copies again each time you use it in a loop. Keep those three facts in mind, reach for structuredClone and plain loops when they fit, and the three dots will serve you well. Our JavaScript closures guide is a good next read.
Frequently asked questions
What is the difference between spread and rest in JavaScript?
Both use three dots. Spread expands an array, string or object into separate values. Rest collects separate values into an array or object, in function parameters or destructuring.
Does the spread operator make a deep copy?
No. It makes a shallow copy, so nested objects and arrays are still shared with the original. Use structuredClone for a deep copy of plain data.
Can I use the spread operator on objects?
Yes. Object spread copies own enumerable properties into a new plain object, and later keys override earlier ones. It does not copy prototype properties or class identity.
Why does Math.max with a spread array throw RangeError?
Each item becomes a separate function argument and engines cap the number of arguments. In our Node 24 test it failed at 200,000 items; use a loop or reduce for large arrays.
Is the spread operator slow?
A single spread is fast. It becomes slow when repeated in a loop, such as spreading the accumulator inside reduce, because each step copies everything built so far.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.