Spread & Rest Operator
Both use the same three-dot syntax
... but do opposite things.
Spread expands an iterable into individual elements —
perfect for cloning, merging, and passing arguments.
Rest collects multiple elements into a single array —
essential for flexible function parameters. Master both and you'll write cleaner,
more expressive JavaScript every day.
... expands
arrays, strings, and objectsSpread vs Rest — Same Syntax, Opposite Roles
The ... token was introduced
in ES6. Context determines whether it's spread or rest —
the same three dots behave differently depending on where they appear in your code:
const merged = [...arr1, ...arr2]; // in array literal
Math.max(...nums); // in function call
const clone = { ...obj }; // in object literal
// REST — appears where parameters are defined
function sum(...nums) { ... } // in function params
const [first, ...rest] = arr; // in destructuring
Spread with Arrays
Spread is most commonly used with arrays — to clone them, combine them, insert elements, or pass them as individual function arguments. Each use avoids mutating the original array:
[...original] creates a new
array with same elements
[...a, ...b] combines two arrays into one new
array
concat() with cleaner, more readable
syntax
// ── Clone an array (shallow copy) ───────────────────────────
const original = [1, 2, 3];
const clone = [...original];
clone.push(4);
console.log(original); // [1, 2, 3] ← untouched
console.log(clone); // [1, 2, 3, 4]
// ── Merge two arrays ────────────────────────────────────────
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b];
console.log(merged); // [1, 2, 3, 4, 5, 6]
// ── Insert elements at specific positions ───────────────────
const middle = [0, ...a, 99, ...b, 100];
console.log(middle); // [0, 1, 2, 3, 99, 4, 5, 6, 100]
// ── Pass array as function arguments ────────────────────────
const nums = [3, 1, 7, 2, 9];
console.log(Math.max(...nums)); // 9 ← spread into individual args
console.log(Math.min(...nums)); // 1
// Before spread, you had to use apply:
Math.max.apply(null, nums); // ← old way, much less readable
// ── Convert string/Set to array ─────────────────────────────
const chars = [..."hello"]; // ["h", "e", "l", "l", "o"]
const unique = [...new Set([1, 2, 2, 3, 1])]; // [1, 2, 3]
// ── Immutable push / unshift pattern ────────────────────────
const todos = ["Buy milk", "Walk dog"];
const withNew = [...todos, "Read book"]; // add to end
const withFirst = ["Wake up", ...todos]; // add to start
Spread with Objects
Object spread (ES2018) copies all
own enumerable properties of an object into a new one.
It's the cleanest way to clone, merge, and override object properties
without Object.assign():
// ── Clone an object ─────────────────────────────────────────
const user = { name: "Alice", age: 28, role: "admin" };
const copy = { ...user };
copy.name = "Bob";
console.log(user.name); // "Alice" ← original untouched
console.log(copy.name); // "Bob"
// ── Merge two objects ────────────────────────────────────────
const defaults = { theme: "dark", lang: "en", fontSize: 14 };
const userPrefs = { lang: "fr", fontSize: 16 };
const config = { ...defaults, ...userPrefs };
console.log(config);
// { theme: "dark", lang: "fr", fontSize: 16 }
// ↑ userPrefs keys override defaults where they clash
// ── Override a single property (immutable update) ────────────
const updated = { ...user, age: 29 };
// { name: "Alice", age: 29, role: "admin" }
// ↑ Original user is unchanged — this is how React/Redux update state
// ── Add a new property while copying ────────────────────────
const withId = { id: 42, ...user };
// { id: 42, name: "Alice", age: 28, role: "admin" }
// ── Order matters — later keys win ──────────────────────────
const a = { x: 1, y: 2 };
const b = { y: 99, z: 3 };
console.log({ ...a, ...b }); // { x: 1, y: 99, z: 3 } ← b.y wins
console.log({ ...b, ...a }); // { y: 2, z: 3, x: 1 } ← a.y wins
// ── Equivalent Object.assign (old way) ──────────────────────
const old = Object.assign({}, defaults, userPrefs); // same result, less clean
structuredClone(obj) (modern) or
JSON.parse(JSON.stringify(obj)).
Rest Parameters
The rest parameter syntax lets a function accept
an indefinite number of arguments as an array. It must always be the
last parameter in the function signature. Unlike the old
arguments object, rest gives you a
real array with all array methods available:
// theRest is a real Array of all remaining arguments
}
// ── Basic rest parameter ─────────────────────────────────────
function sum(...nums) {
return nums.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
console.log(sum()); // 0 ← nums is [] when no args passed
// ── Mix named params with rest ───────────────────────────────
function greetAll(greeting, ...names) {
names.forEach(name => console.log(`${greeting}, ${name}!`));
}
greetAll("Hello", "Alice", "Bob", "Carol");
// Hello, Alice! Hello, Bob! Hello, Carol!
// ── Rest gives a real Array (unlike arguments) ───────────────
function withRest(...args) {
console.log(Array.isArray(args)); // true ← real array
console.log(args.filter(n => n > 0)); // can use map/filter/reduce
}
function withArguments() {
console.log(Array.isArray(arguments)); // false ← NOT a real array
// arguments.filter(...) would throw TypeError
}
// ── Rest in arrow functions ──────────────────────────────────
const multiply = (factor, ...nums) => nums.map(n => n * factor);
console.log(multiply(3, 1, 2, 4)); // [3, 6, 12]
// ── ❌ Rest must be last — this is a SyntaxError ─────────────
// function bad(...first, last) {} // SyntaxError!
// ── Logger with tag ─────────────────────────────────────────
function log(level, ...messages) {
console.log(`[${level.toUpperCase()}]`, ...messages);
}
log("info", "Server started", "on port 3000");
// [INFO] Server started on port 3000arguments object.
Rest gives you a genuine array — you can call .map(), .filter(),
.reduce() directly on it. The arguments object is array-like
but not a real array, doesn't work in arrow functions, and is considered legacy.
Rest in Destructuring
Rest also works inside array and object destructuring to capture the remaining elements after the named ones have been extracted:
// ── Array destructuring with rest ────────────────────────────
const [first, second, ...remaining] = [10, 20, 30, 40, 50];
console.log(first); // 10
console.log(second); // 20
console.log(remaining); // [30, 40, 50]
// ── Skip elements with rest ──────────────────────────────────
const [head, , ...tail] = ["a", "b", "c", "d"];
console.log(head); // "a"
console.log(tail); // ["c", "d"] (skipped "b")
// ── Object destructuring with rest ───────────────────────────
const { name, age, ...otherProps } = {
name: "Alice",
age: 28,
role: "admin",
dept: "Engineering",
};
console.log(name); // "Alice"
console.log(age); // 28
console.log(otherProps); // { role: "admin", dept: "Engineering" }
// ── Omit a property from an object (clean pattern) ──────────
const { password, ...safeUser } = {
id: 1, name: "Bob", email: "bob@x.com", password: "secret123"
};
console.log(safeUser); // { id: 1, name: "Bob", email: "bob@x.com" }
// ↑ Perfect for stripping sensitive fields before sending to client
// ── Function param destructuring with rest ───────────────────
function display({ title, ...rest }) {
console.log(`Title: ${title}`);
console.log("Other data:", rest);
}
display({ title: "JS Guide", pages: 320, author: "Alice" });
// Title: JS Guide
// Other data: { pages: 320, author: "Alice" }Spread in Function Calls
Spread shines when you have arguments stored in an array
and need to pass them to a function that expects individual values.
It replaces the verbose Function.apply()
with clean, readable syntax:
// ── Spread into Math methods ─────────────────────────────────
const scores = [88, 45, 97, 63, 72];
console.log(Math.max(...scores)); // 97
console.log(Math.min(...scores)); // 45
// ── Spread into custom functions ─────────────────────────────
function createUser(name, age, role) {
return { name, age, role };
}
const args = ["Alice", 28, "admin"];
const user = createUser(...args);
console.log(user); // { name: "Alice", age: 28, role: "admin" }
// ── Mix spread with regular args ─────────────────────────────
const extras = [28, "admin"];
const user2 = createUser("Bob", ...extras);
console.log(user2); // { name: "Bob", age: 28, role: "admin" }
// ── Spread + rest together ───────────────────────────────────
function logAll(...items) { // rest: collect into array
console.log(...items); // spread: expand back out
}
logAll("a", "b", "c"); // a b c
// ── Replacing .apply() ──────────────────────────────────────
const arr = [1, 2, 3];
// Old: Math.max.apply(null, arr);
// New: Math.max(...arr); // ← cleaner!Spread vs Rest — Full Comparison
The same ... syntax takes on
a different role depending entirely on its position in your code. Here's the complete
side-by-side breakdown:
| Feature | Spread ... |
Rest ... |
|---|---|---|
| What it does | Expands an iterable into individual elements | Collects multiple elements into one array |
| Direction | Many → one expression | Many args → one array |
| Position in code | Right side of assignment, inside call / literal | Left side of destructuring, function params (last) |
| Works with | Arrays, strings, Sets, Maps, any iterable; objects | Function parameters; array & object destructuring |
| Result type | Individual values (not a new collection by itself) | Always a real Array |
| Common use | Clone, merge, pass args, convert iterables | Variadic functions, capture remaining elements |
| Can appear multiple times? | Yes — spread multiple sources | No — only one rest per signature |
Real-World Use Cases
Spread and rest show up constantly in modern JavaScript codebases — from React state updates to utility functions:
sum(), max(), or log().
.sort() mutates in place — spread first to sort a
copy and keep the original intact.Math.max() or Math.min()
without .apply() by spreading the array.Set, Map keys,
NodeList, or string into a real array instantly with spread.
Try It — Live Editor
Experiment with spread and rest below. Try modifying the arrays, objects, or function calls to see exactly what each operator produces.
Common Patterns & Recipes
These are everyday spread and rest utilities you'll reach for constantly in real JavaScript and frameworks like React:
// ── Sort without mutating original ──────────────────────────
const nums = [3, 1, 4, 1, 5, 9];
const sorted = [...nums].sort((a, b) => a - b);
console.log(nums); // [3, 1, 4, 1, 5, 9] ← untouched
console.log(sorted); // [1, 1, 3, 4, 5, 9]
// ── Unique array via Set + spread ────────────────────────────
const unique = arr => [...new Set(arr)];
unique([1, 2, 2, 3, 1]); // [1, 2, 3]
// ── Omit a key from object (rest trick) ─────────────────────
const omit = (obj, ...keys) => {
const result = { ...obj };
keys.forEach(k => delete result[k]);
return result;
};
omit({ a: 1, b: 2, c: 3 }, "b"); // { a: 1, c: 3 }
// ── Merge arrays with dedup ──────────────────────────────────
const mergeUnique = (a, b) => [...new Set([...a, ...b])];
mergeUnique([1, 2, 3], [2, 3, 4]); // [1, 2, 3, 4]
// ── React-style immutable state update ──────────────────────
const state = { user: "Alice", count: 0, loading: false };
const nextState = { ...state, count: state.count + 1 };
// ↑ Pure update — state is unchanged, nextState is new object
// ── Update item in array immutably ───────────────────────────
const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
const updatedUsers = users.map(u => u.id === 1 ? { ...u, name: "Alicia" } : u);
// [{ id:1, name:"Alicia" }, { id:2, name:"Bob" }]
// ── Curry with rest ─────────────────────────────────────────
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const transform = pipe(x => x * 2, x => x + 1, x => x * x);
console.log(transform(3)); // ((3*2)+1)^2 = 49
[...new Set([1, 2, 2, 3, 1])] produce?function fn(a, b, ...rest), if you call
fn(1, 2, 3, 4, 5), what is the value of rest?
const { x, ...rest } = { x: 1, y: 2, z: 3 }, what is
rest?
- Both spread and rest use
...— context determines the role: spread expands, rest collects. - Spread in arrays — clone with
[...arr], merge with[...a, ...b], pass as function args withfn(...arr). - Spread in objects — clone with
{...obj}, merge with{...a, ...b}, override a property with{...obj, key: newVal}. Later keys win on conflict. - Both spread operations are shallow copies — nested objects are still shared by reference.
- Rest parameters —
function fn(...args)collects all remaining arguments into a real array. Must be the last parameter. - Rest gives you a real Array with full array methods, unlike the legacy
argumentsobject. - Rest in destructuring — captures remaining elements after named ones:
const [head, ...tail] = arrorconst { a, ...rest } = obj. - Use rest destructuring to omit object properties —
const { password, ...safeUser } = user— a clean pattern for stripping sensitive fields.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.