Tutorials JavaScript Spread & Rest Operator
Ch 33 / 78
Chapter 33 Intermediate 7 min read JavaScript

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.

What you'll learn
Spread syntax — how ... expands arrays, strings, and objects
Cloning arrays and objects without mutation
Merging multiple arrays or objects with spread
Rest parameters — collecting remaining function arguments
Difference between spread and rest — same syntax, opposite roles
Real-world patterns — variadic functions, immutable updates, function calls

Spread 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:

...
Spread — Expand
Takes an iterable (array, string, object) and spreads its elements out individually. Appears on the right side of an assignment or inside a function call / array literal / object literal.
Think: "unpack this thing into pieces"
Used in: function calls, array literals, object literals
...
Rest — Collect
Gathers multiple remaining elements into a single array. Appears in function parameter lists and on the left side of destructuring assignments.
Think: "collect the leftover pieces into one"
Used in: function parameters, destructuring
// SPREAD — appears where values are consumed
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 — right side / inside call or literal → expands Rest — left side / inside params → collects into array

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:

Clone — shallow copy
✓ [...original] creates a new array with same elements
✓ Changes to the clone do not affect the original
! Shallow only — nested objects are still shared by reference
Merge & Insert
✓ [...a, ...b] combines two arrays into one new array
✓ Add elements at the start, end, or middle
✓ Replaces concat() with cleaner, more readable syntax
JavaScript — Spread with Arrays
// ── 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():

const result = { ...source1, ...source2, overrideProp: "value" }
source1 — all its own properties are copied in first source2 — its properties are copied in next (later keys win) overrideProp — explicitly set last, overrides any same-named key from sources
JavaScript — Spread with Objects
// ── 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
Shallow Copy Only
Both array and object spread perform a shallow copy. Primitive values (numbers, strings, booleans) are copied by value — safe. But nested objects and arrays are still shared by reference — mutating a nested object in the clone will also mutate the original. For a deep clone, use 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:

function fn(first, second, ...theRest) {
  // theRest is a real Array of all remaining arguments
}
first, second — named individual parameters ...theRest — collects ALL remaining args into a real array Must be last — only one rest param allowed per function
JavaScript — Rest Parameters
// ── 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 3000
Tip — Rest vs arguments
Always prefer rest parameters over the old arguments 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:

JavaScript — Rest in Destructuring
// ── 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:

JavaScript — Spread in Function Calls
// ── 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:

Immutable State Update
React & Redux rely on spread to update state without mutation — creating a new object with one changed field.
spread
Remove Object Property
Destructure the key you want to drop, then collect the rest — clean way to omit sensitive fields like passwords.
rest
Variadic Functions
Build functions that accept any number of arguments — like a custom sum(), max(), or log().
rest
Merge Config / Options
Combine a default config object with user-provided overrides — later keys take priority over earlier ones.
spread
Clone Before Sorting
Array .sort() mutates in place — spread first to sort a copy and keep the original intact.
spread
Forward Props (React)
Spread a props object onto a component — pass all received props through without listing them explicitly.
both
Math on Arrays
Pass an array to Math.max() or Math.min() without .apply() by spreading the array.
spread
Convert Iterables
Turn a Set, Map keys, NodeList, or string into a real array instantly with spread.
spread
⚡
Free Resource
Download our JavaScript Cheat Sheet
Spread, rest, destructuring & modern JS patterns — all on one page.
Get Sheet

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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are everyday spread and rest utilities you'll reach for constantly in real JavaScript and frameworks like React:

JavaScript — Spread & Rest Recipes
// ── 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
Quick Check
What does [...new Set([1, 2, 2, 3, 1])] produce?
Quick Check
In function fn(a, b, ...rest), if you call fn(1, 2, 3, 4, 5), what is the value of rest?
Quick Check
Given const { x, ...rest } = { x: 1, y: 2, z: 3 }, what is rest?
Chapter Summary
  • 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 with fn(...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 arguments object.
  • Rest in destructuring — captures remaining elements after named ones: const [head, ...tail] = arr or const { 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel