Destructuring Get Certified
Destructuring is a concise syntax that lets you unpack values from arrays or properties from objects into distinct variables. It makes code cleaner and more readable, especially when working with function parameters or complex data.
In this lesson you will learn array and object destructuring, renaming, default values, nested patterns, and how to use destructuring in function parameters and loops.
Array Destructuring
Array destructuring extracts values by position. The order of the variables matches the order of the elements.
What this code does: Array destructuring pulls values out by position.
The first element goes into first, the second into second.
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first);
console.log(second);
const colors = ["red", "green", "blue"]; creates a simple array of three color names.const [primary, secondary] = colors; pulls the value at index 0 into primary and the value at index 1 into secondary.console.log(primary); prints red.console.log(secondary); prints green.What this code does: You can skip elements by leaving gaps in the pattern. The second color is ignored; only the first and third are captured.
const colors = ["red", "green", "blue"];
const [primary, , tertiary] = colors;
console.log(primary);
console.log(tertiary);
const scores = [88, 92, 75, 100];const [, second, , fourth] = scores; the empty slots (commas with nothing between them) skip positions. Only the 2nd and 4th values are captured.console.log(second); prints 92.console.log(fourth); prints 100.Default Values in Array Destructuring
If an element is missing or is undefined, a default
value can be supplied.
What this code does: Defaults fill in missing values.
Because the array only has one element, second becomes "none".
const colors = ["red"];
const [first, second = "none"] = colors;
console.log(first);
console.log(second);
const values = [10]; has only one element.const [first, second = 0] = values; first receives 10; because there is no second element, second receives the default value 0.console.log(first); prints 10.console.log(second); prints 0.Rest Element in Array Destructuring
The rest element gathers any remaining items into a new array. It must be the last item in the pattern.
What this code does: The rest element collects everything left over.
first gets the first number; rest gets the remaining ones.
const numbers = [10, 20, 30, 40, 50];
const [first, ...rest] = numbers;
console.log(first);
console.log(rest);
const numbers = [1, 2, 3, 4, 5];const [head, ...tail] = numbers; head receives the first element; the rest operator packs everything that remains into a new array called tail.console.log(head); prints 1.console.log(tail); prints [2, 3, 4, 5].Swapping Variables
Destructuring makes swapping two variables simple without a temporary variable.
What this code does: A classic trick: swap two variables in one line.
After the statement, a and b have exchanged values.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a);
console.log(b);
const user = { name: "Aisha", age: 28, city: "Cairo" };const { name, age } = user; pulls the properties name and age into variables with the same names.console.log(name); prints Aisha.console.log(age); prints 28.// city is not extracted only the requested properties are taken; the rest of the object is left alone.Object Destructuring
Object destructuring extracts values by property name rather than position, using variable names that match the object’s property names.
What this code does: Object destructuring extracts values by property name.
airline and gate are pulled out; order does not matter.
const flight = {
airline: "SkyBridge Air",
flightNumber: "SB482",
gate: "C14"
};
const { airline, gate } = flight;
console.log(airline);
console.log(gate);
const product = {title: "Laptop",price: 999,stock: 12};const { title: productName, price: cost } = product; extracts title but stores it in a variable called productName, and extracts price into cost.console.log(productName); prints Laptop.console.log(cost); prints 999.Renaming Variables While Destructuring
You can assign a destructured property to a variable with a different name using a colon.
What this code does: Rename while destructuring with a colon.
flightNumber is stored in a variable called confirmationCode.
const flight = {
airline: "SkyBridge Air",
flightNumber: "SB482"
};
const { flightNumber: confirmationCode } = flight;
console.log(confirmationCode);
const settings = { theme: "dark" };const { theme, language = "en" } = settings; theme receives "dark"; because language is undefined, the default "en" is used.console.log(theme); prints dark.console.log(language); prints en.undefined, not for other falsy values such as 0 or "".
Notice that only confirmationCode exists after this —
there is no variable named flightNumber in this
example.
Default Values in Object Destructuring
A default value is used if the property doesn’t exist on the
object, or is explicitly undefined.
What this code does: Defaults work for objects too.
When seatClass is missing, it becomes "Economy".
const flight = {
airline: "SkyBridge Air"
};
const { airline, seatClass = "Economy" } = flight;
console.log(airline);
console.log(seatClass);
const config = { host: "localhost", port: 3000, debug: true };const { host, ...rest } = config; host receives the host value; the rest operator packs every remaining property into a new object called rest.console.log(host); prints localhost.console.log(rest); prints { port: 3000, debug: true }.Renaming and default values can also be combined together.
What this code does: You can rename and provide a default at the same time.
The empty object has no seatClass, so cabin becomes "Economy".
const flight = {};
const { seatClass: cabin = "Economy" } = flight;
console.log(cabin);
function connect({ host = "localhost", port = 80 } = {}) { destructures the parameter directly. Defaults are supplied both for individual properties and for the whole argument (the trailing = {}).console.log("Connecting to " + host + ":" + port);}Nested Destructuring
Destructuring can reach into nested objects and arrays in a single statement.
What this code does: Nested destructuring reaches into objects and arrays in one step. City, country, and the first checkpoint are extracted together.
const shipment = {
trackingId: "TRK-9081",
destination: {
city: "Lisbon",
country: "Portugal"
},
checkpoints: ["Warehouse", "Customs", "Local Hub"]
};
const {
destination: { city, country },
checkpoints: [firstCheckpoint]
} = shipment;
console.log(city);
console.log(country);
console.log(firstCheckpoint);
const order = {id: "ORD-42",customer: {name: "Noah",email: "noah@example.com"},items: [{ sku: "A1", qty: 2 },{ sku: "B3", qty: 1 }]};const {id,customer: { name }, reaches into the nested customer object and pulls only the name property.items: [{ sku: firstSku }] reaches into the items array, takes the first element, and extracts its sku.} = order;
Note that in this example, no variable named
destination or checkpoints is created —
only the more deeply nested variables are.
Destructuring in Function Parameters
Destructuring is especially useful directly in a function’s parameter list, avoiding repeated property access inside the function body.
What this code does: Destructuring in function parameters unpacks the argument object.
Gate defaults to "TBD" when it is not provided.
function printBoardingPass({ airline, flightNumber, gate = "TBD" }) {
console.log(airline + " " + flightNumber + " — Gate " + gate);
}
printBoardingPass({ airline: "SkyBridge Air", flightNumber: "SB482" });
const pairs = [["x", 10], ["y", 20]];const [[, xVal], [, yVal]] = pairs; each inner array is itself destructured; the first element of each pair is skipped and the second is kept.console.log(xVal); prints 10.console.log(yVal); prints 20.Array destructuring can also be used in parameters, which is common when working with functions that return a fixed-size array.
What this code does: Array destructuring works in parameters too. The function receives a min/max pair and formats a range string.
function describeRange([min, max]) {
return "Between " + min + " and " + max;
}
console.log(describeRange([10, 50]));
const point = { x: 5, y: 12 };let { x, y } = point; first extracts the current values.[x, y] = [y, x]; uses array destructuring on the right-hand side to swap the two variables in one statement.console.log(x, y); prints 12 5.Destructuring While Looping
Destructuring pairs naturally with for...of when
looping over an array of objects or the result of
Object.entries().
What this code does: Destructure each object while looping with for...of.
id and weightKg are available directly in the loop body.
const packages = [
{ id: "P-1", weightKg: 2.5 },
{ id: "P-2", weightKg: 5.0 }
];
for (const { id, weightKg } of packages) {
console.log(id + ": " + weightKg + " kg");
}
const packages = [{ id: "P-1", weightKg: 2.5 },{ id: "P-2", weightKg: 5.0 }];for (const { id, weightKg } of packages) { on every iteration the current object is destructured so id and weightKg are available directly.console.log(id + ": " + weightKg + " kg");}Practical Example
Let’s use destructuring to cleanly extract and process information from an API-like response object.
What this code does: Deep nesting can still be unpacked in one pattern. Status, username, and the first role are pulled from the API response.
const apiResponse = {
status: 200,
data: {
user: {
username: "michael_dev",
roles: ["editor", "reviewer"]
}
}
};
const {
status,
data: {
user: { username, roles: [primaryRole] }
}
} = apiResponse;
console.log("Status:", status);
console.log("Username:", username);
console.log("Primary role:", primaryRole);
const apiResponse = {status: 200,data: {user: {username: "michael_dev",roles: ["editor", "reviewer"]}}};const {status,data: {user: { username, roles: [primaryRole] } pulls username and the first element of the roles array in one step.}} = apiResponse;console.log("Status:", status);console.log("Username:", username);console.log("Primary role:", primaryRole); prints editor.Destructuring Syntax Overview
| Goal | Array Destructuring | Object Destructuring |
|---|---|---|
| Basic extraction | const [a, b] = arr | const { a, b } = obj |
| Skip / rename | const [, b] = arr | const { a: renamed } = obj |
| Default value | const [a = 1] = arr | const { a = 1 } = obj |
| Gather the rest | const [a, …rest] = arr | const { a, …rest } = obj |
Common Mistakes With Destructuring
- Using square brackets for object destructuring, or curly braces for array destructuring, instead of matching the data structure being destructured.
- Forgetting that default values only apply when a value is
undefined, not for other falsy values like0or"". - Destructuring a property that doesn’t exist and forgetting to provide a default, resulting in
undefined. - Placing a rest element anywhere except last in the pattern, which causes a syntax error.
- Destructuring deeply nested data without checking that each level actually exists, risking a
TypeErrorwhen a property is missing.
Best Practices for Destructuring
- Use object destructuring in function parameters for functions that accept many optional settings.
- Provide sensible default values for properties that might be missing.
- Keep destructuring patterns readable — avoid excessive nesting in a single statement if it hurts clarity.
- Use array destructuring when working with fixed-size, position-based data, like coordinates or ranges.
- Combine destructuring with
for...ofwhen looping over arrays of objects for cleaner code.
Quick Summary
- Array destructuring extracts values by position; object destructuring extracts values by property name.
- Both support default values, used when a value is
undefined. - Object destructuring can rename variables using a colon.
- A rest element gathers remaining values into a new array or object, and must be last in the pattern.
- Destructuring works in variable declarations, function parameters, and loops.
- Nested destructuring can extract values from deeply nested objects and arrays in one statement.
Try It Yourself
Modify the code below. Try renaming a variable, adding a default value, or destructuring a new property from the object.
What this code does: Practice example: mix object and array destructuring. Try renaming a variable or adding a default, then click Test My Code.
const event = {
name: "Tech Meetup",
location: "Community Hall",
attendees: ["Noah", "Aisha", "Liam"]
};
const { name, attendees: [firstAttendee] } = event;
console.log(name);
console.log(firstAttendee);
const event = {name: "Tech Meetup",location: "Community Hall",attendees: ["Noah", "Aisha", "Liam"]};const { name, attendees: [firstAttendee] } = event; extracts the name property and, from the attendees array, the first element only.console.log(name);console.log(firstAttendee); prints Noah. Try renaming a variable or adding a default.Tip: A quick way to remember which syntax to use: square brackets[]match arrays because order matters; curly braces{}match objects because names matter.
Understanding destructuring is essential before moving on to the spread and rest operators in more depth, modules, and more advanced JavaScript concepts.
🧪 Test Your JavaScript Code
Edit the code on the left and click “Run Code” to see the console output on the right.
Click “Run Code” to see the output here.
Code Explanation
The complete example stays visible. Use Previous and Next to move through its logical blocks.
Select Next to begin exploring the code.