Academic Block

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);

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);

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);

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);

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);

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);

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);

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);

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);

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);

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" });

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]));

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");
}

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);

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 like 0 or "".
  • 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 TypeError when 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...of when 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);
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.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close