Difficulty: Beginner
What are destructuring, spread and rest in JavaScript, and how are they used in real code?
Destructuring unpacks values from arrays or properties from objects into variables in a single statement, such as const { id, amount } = payment. The ... syntax does two opposite jobs: as spread it expands an array or object into individual elements or properties, and as rest it collects the remaining elements, properties or arguments into a new array or object. Which one it is depends on where it appears.
const { name, city } = user. You can rename ({ name: fullName }), set defaults ({ role = 'student' }) and go nested ({ address: { pincode } }).const [first, second] = list. You can skip items with holes (const [, second] = list) and swap variables without a temp: [a, b] = [b, a].undefined, not when it is null. const { limit = 10 } = { limit: null } gives limit === null.null or undefined throws a TypeError, so guard with a default: function f({ page = 1 } = {}).| Spread | Rest | |
|---|---|---|
| Where it appears | Right side, function call args, array/object literals | Left side of destructuring, function parameters |
| What it does | Expands one iterable/object into many | Gathers many into one array/object |
| Example | Math.max(...scores) | function log(level, ...msgs) |
| Position rule | Anywhere, multiple times | Must be last, only once |
Rest parameters replace the old arguments object, which is array-like but not a real array and does not exist in arrow functions.
{ ...defaults, ...options } merges objects, with later properties winning. [...a, ...b] concatenates arrays. This is the backbone of immutable updates in React and Redux: setUser({ ...user, city: 'Bengaluru' }) creates a new object so React sees a changed reference.
The key limitation: spread makes a shallow copy. Nested objects are still shared, so changing copy.address.city changes the original too. For a true deep copy use structuredClone(obj), available in all modern browsers and Node 17+. It handles Dates, Maps, Sets and cycles, but not functions or class prototypes.
function Card({ title, children, ...rest }) then <div {...rest}>.const [count, setCount] = useState(0) is array destructuring.const { data: { items = [] } = {} } = response.const { password, ...safeUser } = user.import { useState } from 'react') but are module syntax, not destructuring; you cannot use defaults or nesting there.const payment = {
id: 'pay_29QQoUBi66xm2f',
amount: 50000,
method: 'upi',
customer: { name: 'Ananya', contact: { city: 'Pune' } },
notes: null,
};
const {
id: paymentId,
currency = 'INR',
customer: { name, contact: { city } },
notes = 'none',
} = payment;
console.log(paymentId, currency, name, city, notes);
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b);
currency gets its default because it is undefined, but notes stays null because defaults only apply to undefined. Array destructuring swaps without a temp variable.
function logEvent(level, ...messages) {
console.log(`[${level}]`, messages.join(' | '));
}
logEvent('INFO', 'order placed', 'id=101', 'city=Delhi');
const user = { id: 7, email: 'a@b.com', password: 'hash', role: 'admin' };
const { password, ...safeUser } = user;
console.log(safeUser);
Rest collects leftover arguments into a real array, and object rest is a clean way to drop a field before sending a response.
const original = { name: 'Rohan', address: { city: 'Mumbai' } };
const shallow = { ...original };
shallow.address.city = 'Chennai';
console.log(original.address.city); // changed!
const deep = structuredClone(original);
deep.address.city = 'Kolkata';
console.log(original.address.city); // unchanged
const merged = { ...{ theme: 'light', lang: 'en' }, ...{ theme: 'dark' } };
console.log(merged);
Spread copies only the top level, so nested objects are shared. structuredClone copies the whole tree. When merging, later keys win.
Destructuring, Spread Syntax, Rest Parameters, Default Values, Shallow Copy