Spread & Rest
The ... syntax does two opposite things depending on context: spread expands an iterable into individual elements, while rest collects multiple elements into a single array.
What is the difference between spread and rest in JavaScript?
Both use ..., but they work in opposite directions. Spread expands an array or object into individual items: [...a, ...b] merges arrays and { ...defaults, ...options } merges objects. Rest collects several items into one array or object: function sum(...nums) or const { id, ...others } = obj.
const merged = [...arr1, ...arr2];
const copy = { ...user, name: "New" }; // later keys win
Math.max(...[3, 9, 2]); // 9
function log(first, ...others) { … } // rest parameter
const { password, ...safeUser } = user; // rest in destructuringSpread — Expand
Spread expands an iterable (array, string, Set, Map…) into individual elements. Used in array literals, object literals, and function calls.
[...arr][...a, ...b]fn(...args){ ...obj }{ ...defaults, ...override }Rest — Collect
Rest collects multiple values into a single array. Used in function parameters and destructuring — always the last element.
function f(...args) {}function f(a, b, ...rest) {}const [h, ...tail] = arrconst { a, ...rest } = objfunction omit({ pass, ...u }) { return u; }Immutable Update Patterns
Spread is the foundation of React/Redux-style immutable state updates. Instead of mutating state directly, create a new object/array with the changes spread in.
Update a field
const next = { ...state, count: state.count + 1 };Add to array
const next = [...items, newItem];Remove from array
const next = items.filter(x => x.id !== id);Shallow copy warning: Spread only clones the top level. Nested objects are still shared references. For deep cloning use structuredClone(obj) (modern) or a library like Lodash's _.cloneDeep.
Common Pitfalls
Interactive Examples
Code Editor
<pre id="out"></pre>Preview
Spread and rest — step by step
Spread — expanding iterables
The spread operator (...) expands an iterable (array, string, Set, Map) into individual elements. [...arr1, ...arr2] creates a shallow copy of both arrays merged. {...obj1, ...obj2} merges objects (later keys overwrite earlier ones). [..string] splits a string into characters — correctly handles Unicode emoji and multi-codepoint characters unlike split('').
🎯 Quick Check
What does const b = { ...a } do if a has nested objects?
Spread and Rest: summary
Key points
- Spread makes shallow copies: nested objects are still shared.
- In object spread, properties on the right override those on the left.
- The rest parameter must be the last parameter.
Frequently asked questions
›How do I copy an array in JavaScript?
Use [...arr] or arr.slice() for a shallow copy, and structuredClone(arr) for a deep copy.