Suppose, you receive a user profile from an API. You need the name for a greeting, the city for delivery, and a new settings object with one value changed. JavaScript gives you a few short ways to do this: destructuring, spread syntax, and rest syntax.
These features appear in React components, Node.js handlers, and everyday JavaScript. The three dots can feel confusing because their meaning changes with their position. This guide explains each use through small examples, then brings them together in a practical order example. Every code block starts fresh.
What do destructuring, spread, and rest do?
Destructuring reads values into variables. Spread expands values into a new array, object, or function call. Rest collects the remaining values into an array or object. Once you look at where the syntax appears, the meaning becomes easier to follow.
Feature | Example | Purpose |
|---|---|---|
Destructuring |
| Read a property into a variable |
Spread |
| Expand items into a new array |
Rest |
| Collect remaining items |
If arrays and objects are new to you, read JavaScript Array Methods and JavaScript Objects Explained first. We will use both kinds of data here.
Array destructuring reads by position
Imagine an array containing three cities. Destructuring lets you give names to the first two positions in one statement. You can skip a position with an extra comma.
const cities = ["Dhaka", "Sylhet", "Khulna"];
const [firstCity, secondCity] = cities;
const [, , thirdCity] = cities;
console.log(firstCity); // "Dhaka"
console.log(secondCity); // "Sylhet"
console.log(thirdCity); // "Khulna"
console.log(cities.length); // 3Array destructuring follows the iterable’s order. For a normal array, that means the first variable receives the first item. Reading these values leaves the array unchanged.
Object destructuring reads by property name
An object stores named values. The property name in the pattern selects what to read. The order of the properties in the pattern does not need to match the object.
const user = { name: "Shariar", city: "Dhaka", role: "developer" };
const { city, name } = user;
console.log(name); // "Shariar"
console.log(city); // "Dhaka"
console.log(user.role); // "developer"You can rename a variable while reading a property. This helps when two objects have a name field or when a clearer local name makes the code easier to understand.
const user = { name: "Shariar", city: "Dhaka" };
const { name: displayName } = user;
console.log(displayName); // "Shariar"
console.log(user.name); // "Shariar"The name before the colon is the property to read. The name after it is the variable being created. This statement creates displayName. It does not create a local variable called name.
Defaults apply to undefined values
A destructuring default is used when a value is missing or undefined. Values such as null, zero, false, and an empty string keep their existing values.
const settings = { fee: 0, note: null, enabled: false };
const {
fee = 60,
note = "No note",
enabled = true,
currency = "BDT"
} = settings;
const [first = 10, second = 20] = [undefined, null];
console.log(fee); // 0
console.log(note); // null
console.log(enabled); // false
console.log(currency); // "BDT"
console.log(first); // 10
console.log(second); // nullIf you want a fallback for both null and undefined, use the nullish coalescing operator, ??. For example, settings.note ?? "No note" produces "No note" in this example. Choose the fallback based on what the data means.
Handle nested API data carefully
Nested destructuring can read a value inside another object. This can be convenient when the data shape is reliable. If part of a response can be missing, think about each level that may be null or undefined.
const response = {
user: { name: "Shariar", address: { city: "Dhaka" } }
};
const { user: { address: { city } } } = response;
console.log(city); // "Dhaka"
const incomplete = { user: { address: null } };
const displayCity = incomplete.user?.address?.city ?? "City not added";
console.log(displayCity); // "City not added"A pattern such as { address: { city } = {} } handles an undefined address. It still throws if address is null. Optional chaining makes reading a single deeply optional value easier. It checks for null and undefined at the positions where you place ?.. It does not validate that an API value has the expected type.
Destructure function parameters
A function can read named options directly in its parameter list. Defaults make the call convenient when some options are omitted.
function deliveryLabel({ city = "Dhaka", fee = 60 } = {}) {
return `${city}: Tk ${fee}`;
}
console.log(deliveryLabel()); // "Dhaka: Tk 60"
console.log(deliveryLabel({ city: "Sylhet", fee: 0 })); // "Sylhet: Tk 0"
console.log(deliveryLabel({})); // "Dhaka: Tk 60"The outer = {} handles a missing argument or an explicit undefined argument. Calling deliveryLabel(null) still throws a TypeError because the pattern tries to destructure null. For external input, validate the value before passing it into this function.
Spread adds and combines array items
Inside an array literal, spread reads items from an iterable and places them into the new array. Arrays and strings are common iterables. A regular object literal is not iterable by default.
const existing = ["Notebook", "Pen"];
const updated = [...existing, "Pencil"];
const combined = [...existing, ...["Eraser", "Ruler"]];
console.log(updated); // ["Notebook", "Pen", "Pencil"]
console.log(combined); // ["Notebook", "Pen", "Eraser", "Ruler"]
console.log(existing); // ["Notebook", "Pen"]
console.log(updated === existing); // falseThe updated array is a separate outer array. If its items are objects, those objects remain shared unless you create new ones too. We will explore that below.
Spread copies and merges object properties
Inside an object literal, spread copies own enumerable properties from the source, including enumerable symbol properties. For ordinary data objects, this is a useful way to create an updated version.
const defaults = { theme: "light", language: "en" };
const preferences = { theme: "dark" };
const settings = { ...defaults, ...preferences, language: "bn" };
console.log(settings.theme); // "dark"
console.log(settings.language); // "bn"
console.log(defaults.theme); // "light"When the same key appears more than once, the later value wins. Reversing the order of defaults and preferences changes which theme wins. Object spread creates a new ordinary object. It does not preserve the source object’s prototype or property descriptors.
Spread can pass an array as function arguments
A function may expect separate arguments while your values are stored in an array. Spread can expand the array into the call.
const prices = [80, 20, 10];
console.log(Math.max(...prices)); // 80
console.log(Math.min(...prices)); // 10Use this for reasonably sized collections. JavaScript engines have limits on the number of arguments in a call, so expanding a huge array can fail. For large inputs, choose an approach that processes the collection without turning every item into an argument.
Rest collects remaining array items
On the left side of a destructuring declaration, ... collects the remaining items. The result here is a new array. The rest element must come last, with no trailing comma after it.
const tasks = ["Write", "Review", "Publish"];
const [nextTask, ...remainingTasks] = tasks;
console.log(nextTask); // "Write"
console.log(remainingTasks); // ["Review", "Publish"]
console.log(tasks); // ["Write", "Review", "Publish"]Rest collects remaining object properties
Object rest collects the own enumerable properties that the earlier parts of the pattern did not select. This can help build a smaller object for a particular use.
const product = { id: 1, name: "Notebook", price: 80, stock: 12 };
const { stock, ...displayProduct } = product;
console.log(stock); // 12
console.log(Object.keys(displayProduct)); // ["id", "name", "price"]
console.log(Object.hasOwn(displayProduct, "stock")); // false
console.log(product.stock); // 12Removing a field this way only removes that particular property from the new object. For a public API response, an explicit list of allowed output fields is often easier to review as the source object grows.
Rest parameters collect function arguments
In a function parameter list, a rest parameter receives remaining arguments as an actual array. It must be the final parameter. You can then use normal array methods on it.
function calculateTotal(deliveryFee, ...prices) {
return prices.reduce((total, price) => total + price, deliveryFee);
}
console.log(calculateTotal(60, 80, 20)); // 160
console.log(calculateTotal(60)); // 60In calculateTotal(60, 80, 20), deliveryFee receives 60 and prices receives [80, 20]. This is a different use from Math.max(...prices): the parameter collects values, while the call expands them.
Spread creates a shallow copy
A shallow copy creates a new outer container but keeps references to nested objects. That means a change deep inside a copied object can still affect the original.
const user = { name: "Shariar", address: { city: "Dhaka" } };
const copy = { ...user };
copy.address.city = "Sylhet";
console.log(copy === user); // false
console.log(copy.address === user.address); // true
console.log(user.address.city); // "Sylhet"To change the address independently, create a new address object as well. Copy each level you need to update.
const user = {
name: "Shariar",
address: { city: "Dhaka", area: "Mohammadpur" }
};
const updated = {
...user,
address: { ...user.address, city: "Sylhet" }
};
console.log(user.address.city); // "Dhaka"
console.log(updated.address.city); // "Sylhet"
console.log(updated.address.area); // "Mohammadpur"
console.log(updated.address === user.address); // falseThe same issue applies to array copies. [...products] copies the outer array while retaining references to its product objects. For an update to one product, map over the list and return a new object for the item you change.
Practical example: calculate and update an order
Imagine an order with two notebooks at Tk 80 each and one pen at Tk 20. Delivery costs Tk 60. We can destructure the order, use rest in a calculation function, spread the line totals into a call, and build an updated delivery address.
const order = {
id: "ORD-101",
customer: {
name: "Shariar",
address: { city: "Dhaka", area: "Mohammadpur" }
},
items: [
{ name: "Notebook", price: 80, quantity: 2 },
{ name: "Pen", price: 20, quantity: 1 }
],
deliveryFee: 60
};
const { id: orderNumber, items, deliveryFee = 0 } = order;
const lineTotals = items.map(({ price, quantity }) => price * quantity);
function addAmounts(...amounts) {
return amounts.reduce((total, amount) => total + amount, 0);
}
const total = addAmounts(...lineTotals, deliveryFee);
const updatedOrder = {
...order,
customer: {
...order.customer,
address: { ...order.customer.address, area: "Dhanmondi" }
}
};
console.log(orderNumber); // "ORD-101"
console.log(lineTotals); // [160, 20]
console.log(total); // 240
console.log(order.customer.address.area); // "Mohammadpur"
console.log(updatedOrder.customer.address.area); // "Dhanmondi"
console.log(updatedOrder.items === order.items); // trueThe items array is reused because this update only changes the delivery area. The customer and address objects are new. These examples use whole taka amounts for clarity. An application handling fractional currency also needs a deliberate representation and rounding strategy.
Common mistakes and how to fix them
A few small syntax details account for many errors. Check these first when your output is surprising.
Using array destructuring on a regular object
const [name] = { name: "Shariar" } throws because an ordinary object literal is not iterable. Use const { name } = user to select a named property. Arrays and function calls also require an iterable when you spread values into them, while object spread works with enumerable properties.
Expecting an empty-object default to handle null
A default only applies to undefined. If null is an accepted input meaning “no options,” normalize it first, such as const options = input ?? {}. You still need validation when input may contain other unexpected types.
Assigning destructured values to existing variables
When an object assignment pattern starts a statement, wrap it in parentheses so JavaScript treats the braces as an assignment pattern.
let city;
({ city } = { city: "Dhaka" });
console.log(city); // "Dhaka"Assuming destructuring makes a copy
Destructuring reads values. If the selected value is an object, the variable receives a reference to that same object. For example, const { address } = user does not clone the address. Object rest creates a new outer object, but its nested values can still be shared.
Renaming a field and expecting the old variable name
const { name: displayName } = user creates displayName. Use that name afterwards. The pattern reads user.name without changing the property name on the source object.
Frequently asked questions
These short answers can help you review the differences after working through the examples.
Are spread and rest the same feature?
They use the same three dots in different positions. Spread expands values in an array literal, object literal, or function call. Rest gathers remaining values in a destructuring pattern or function parameter list.
Can I rename a property and set a default together?
Yes. const { name: displayName = "Guest" } = user reads name into displayName and uses "Guest" when the value is undefined.
Does spreading an array or object change the original?
The spread operation does not assign changes to the source. It creates or contributes values to the target expression. Nested objects may still be shared, so a later update to a shared object can affect both containers. Accessor properties can also run code when their values are read.
Should I destructure every property I use?
Use destructuring when it improves clarity. For one optional nested value, optional chaining may be simpler. When several sources have similar field names, keeping the object name in expressions can make the code easier to follow.
Practise with your own data
Create a student object with a name, marks array, and nested address. Destructure the name with a new variable name. Use array rest to separate the first mark from the remaining marks. Create a new student with an updated city, then print both addresses to confirm the original stays the same.
Once these examples feel familiar, try reading an API response from your own project. Choose two fields to destructure, one optional value to handle, and one nested field to update. Keep the patterns short enough that another developer can understand the data flow at a glance.
Comments
Join the discussion. Sign in with Google to post; your email is never shown.