Spread and Rest Operators in JavaScript Explained with Examples
Modern JavaScript provides powerful syntax to work with arrays, objects, and function arguments. Two closely related features introduced in ES6 are the spread (...) and rest (...) operators.
They look the same, but they behave differently depending on where and how they are used.
In this tutorial, you’ll learn:
what spread and rest operators are
how they differ
common use cases
practical examples
common mistakes
Let’s start from the basics.
What Is the Spread Operator?
The spread operator (...) is used to expand an iterable (array, string, or object) into individual elements.
Think of it as unpacking values.
Spread Operator with Arrays
Copying an Array
const numbers = [1, 2, 3];
const copy = [...numbers];
console.log(copy);
This creates a shallow copy.
Merging Arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
console.log(merged);
Adding Elements
const arr = [1, 2, 3];
const newArr = [0, ...arr, 4];
Spread Operator with Objects
Copying Objects
const user = { name: "Alex", age: 25 };
const copy = { ...user };
Merging Objects
const defaults = { theme: "dark" };
const settings = { theme: "light", fontSize: 16 };
const config = { ...defaults, ...settings };
Later properties overwrite earlier ones.
Spread Operator in Function Calls
const nums = [5, 10, 15];
Math.max(...nums);
Without spread, this wouldn’t work.
What Is the Rest Operator?
The rest operator (...) is used to collect multiple values into a single variable.
Think of it as packing values.
Rest Operator in Function Parameters
Collecting Arguments
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4);
Mixing Named and Rest Parameters
function log(first, ...others) {
console.log(first);
console.log(others);
}
Rest must always be last.
Rest Operator with Destructuring
Array Destructuring
const [first, ...rest] = [10, 20, 30, 40];
console.log(rest); // [20, 30, 40]
Object Destructuring
const user = { name: "Alex", age: 25, role: "admin" };
const { name, ...details } = user;
console.log(details);
Spread vs Rest: Key Differences
| Spread | Rest |
| Expands values | Collects values |
| Used in function calls | Used in parameters |
| Used on right side | Used on left side |
| Unpacks data | Packs data |
Common Mistakes
❌ Confusing spread with rest
They look identical but depend on context.
❌ Mutating original data
Spread creates shallow copies only.
❌ Using rest incorrectly
function test(...a, b) {} // error
Rest must be last.
Real-World Use Cases
✔ Handling API responses
✔ React props
✔ Immutable state updates
✔ Flexible function arguments
Mental Model
Spread opens a box.
Rest collects items into a box.
Conclusion
The spread and rest operators make JavaScript:
more expressive
less verbose
easier to work with data
Once you understand the context-based behavior, they become indispensable tools.