Lesson 62 of 296
Spread, rest and destructuring
What you will learn
- Spread: expanding arrays and objects
- Rest: collecting the remaining items
- Destructuring arrays and objects
- Default values and renaming
- Destructuring in function parameters
- Common patterns: swap, update state, remove a key
On this page
Spread ...
The spread syntax ... expands an array or object into its individual parts.
Arrays:
const a = [1, 2];
const b = [3, 4];
const all = [...a, ...b]; [1, 2, 3, 4]
const copy = [...a]; a new array
const more = [0, ...a, 5]; [0, 1, 2, 5]
Math.max(...[3, 9, 2]); 9
[..."hey"] ["h", "e", "y"]Objects:
const base = { theme: "light", lang: "en" };
const settings = { ...base, lang: "fr" }; { theme: "light", lang: "fr" }When keys clash, the later one wins. This is the standard way to update one property while keeping the rest, used everywhere in React:
const updatedUser = { ...user, email: "new@example.com" };Spread makes a shallow copy (Lesson 63).
Rest ...
Rest uses the same ... syntax but does the opposite: it collects several values into one array or object. It appears on the left side of = or in function parameters.
Function parameters:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); 10numbers is a real array of every argument. A rest parameter must be last.
function log(level, ...messages) {
console.log(`[${level}]`, ...messages);
}
log("INFO", "Server started", "on port 3000");Spread or rest? How to tell
- Spread: used where values are expected (inside
[ ],{ }or a function call). It expands. - Rest: used where variables are being created (function parameters, the left of a destructuring). It collects.
Array destructuring
Destructuring takes values out of an array or object and puts them into variables, in one line.
const colours = ["red", "green", "blue"];
const [first, second] = colours; first = "red", second = "green"
const [, , third] = colours; skip items with commas: "blue"
const [head, ...tail] = colours; head = "red", tail = ["green", "blue"]
const [a = "none", b, c, d = "none"] = colours; defaults for missing items: d = "none"Swap two variables:
let x = 1;
let y = 2;
[x, y] = [y, x]; x = 2, y = 1This is exactly what React's useState uses:
const [count, setCount] = useState(0);Object destructuring
Values are matched by key name, not position.
const user = { name: "Sam", age: 30, city: "Leeds" };
const { name, age } = user; name = "Sam", age = 30
const { name: fullName } = user; rename: fullName = "Sam"
const { country = "UK" } = user; default: country = "UK"
const { name: n, ...rest } = user; rest = { age: 30, city: "Leeds" }Remove a key without mutating:
const { password, ...safeUser } = userFromDb;safeUser has every property except password. Very useful before sending user data to the front end.
Nested:
const order = { id: 7, customer: { address: { city: "York" } } };
const { customer: { address: { city } } } = order; city = "York"If customer is missing, this throws an error. Use defaults or optional chaining for data that may be missing.
Destructuring in function parameters
function createUser({ name, email, role = "user" }) {
return { name, email, role };
}
createUser({ email: "sam@example.com", name: "Sam" });Benefits:
- Arguments are named, so their order does not matter.
- Optional values get defaults.
- The function signature shows exactly what it needs.
This is the standard way React components receive props:
function Button({ label, onClick, disabled = false }) { ... }If the whole object might be missing, give it a default too:
function connect({ host = "localhost", port = 5432 } = {}) { ... }
connect(); worksCommon mistakes
- Putting the rest element anywhere but last.
- Confusing spread and rest.
- Destructuring from
undefined:const { a } = undefinedthrows a TypeError. - Thinking spread makes a deep copy.
- Defaults only apply to
undefined, notnull.
How to say it in an interview
"Spread expands an iterable or object into individual elements, which I use to copy and merge arrays and objects immutably, for example updating one property of state. Rest collects remaining elements into an array or object, in function parameters or destructuring. Destructuring unpacks values into variables, by position for arrays and by key for objects, with renaming and default values. Destructuring an options object in parameters gives named arguments, which is how React props work."
Key words
| Word | Meaning |
|---|---|
| Spread | ... that expands values |
| Rest | ... that collects values |
| Destructuring | Unpacking values from arrays or objects into variables |
| Default value | A value used when the original is undefined |
| Shallow copy | A copy where nested objects are still shared |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.