Welcome. This first module strengthens the modern JavaScript patterns that show up constantly in MERN work: handling API data, writing clean React components, and shaping values passed between Express layers. You already use asynchronous JavaScript and DOM code; destructuring will make the data-handling parts of that code shorter while preserving clarity.
In this lesson, you will learn to extract selected values from arrays and objects with destructuring. The important distinction is that arrays are unpacked by position, while objects are unpacked by property name. You will also use defaults, renamed variables, nested patterns, and function parameters—the forms you will meet most often in application code.

Destructuring is an assignment pattern
Usually, extracting data means repeatedly reaching into a collection:
const product = {
id: "p42",
title: "Mechanical Keyboard",
price: 89
};
const title = product.title;
const price = product.price;
That is perfectly valid. But when several values are needed, destructuring lets the left side of an assignment describe the shape of the data you want to take:
const { title, price } = product;
console.log(title); // "Mechanical Keyboard"
console.log(price); // 89
The source object has not been changed. Destructuring is not deletion, conversion, or cloning; it simply creates bindings for values taken from the existing structure.
If an extracted value is itself an object or array, the new variable refers to that same nested value:
const user = {
name: "Asha",
preferences: { theme: "dark" }
};
const { preferences } = user;
preferences.theme = "light";
console.log(user.preferences.theme); // "light"
So destructuring is about convenient access, not automatically making independent deep copies.
Why Is Array/Object Destructuring So Useful And How To Use It
Watch “Why Is Array/Object Destructuring So Useful And How To Use It” from Web Dev Simplified for a compact visual walkthrough. It connects the syntax to the repetitive property and index access it replaces.
Watch the core idea and the array pattern, stopping just before the discussion of rest syntax; that syntax is the focus of the next lesson. Then watch array defaults, object matching, and nested extraction. Finish with function parameters, which is especially relevant to upcoming React component props and backend helper functions. Notice throughout that arrays rely on position, whereas objects rely on keys.
Arrays: extract values by their position
Use square brackets on the left when the value on the right is an array or another iterable value such as a string.
const routeParts = ["products", "p42", "reviews"];
const [resource, productId, childResource] = routeParts;
console.log(resource); // "products"
console.log(productId); // "p42"
console.log(childResource); // "reviews"
Conceptually, this is equivalent to:
const resource = routeParts[0];
const productId = routeParts[1];
const childResource = routeParts[2];
The difference is that destructuring makes the relationship between the array’s layout and its values visible in one place.
Skipping positions
A comma can reserve a position without creating a variable. This is useful when a function or API convention returns a tuple-like array and you only need selected positions.
const coordinates = [18.5204, 73.8567, 553];
const [latitude, , elevation] = coordinates;
console.log(latitude); // 18.5204
console.log(elevation); // 553
The empty space between the commas says: “ignore the second element.”
Defaults for missing values
If the array does not contain an element at a requested position, the variable becomes undefined by default. You can provide a fallback directly in the destructuring pattern:
const responseParts = ["success", { id: "p42" }];
const [status, data, message = "No message supplied"] = responseParts;
console.log(status); // "success"
console.log(message); // "No message supplied"
A default applies only when the extracted value is undefined or absent. It does not replace a value such as false, 0, an empty string, or null.
const settings = [false, 0, "", null, undefined];
const [
isEnabled = true,
limit = 20,
label = "Untitled",
selectedId = "none",
fallbackValue = "used"
] = settings;
console.log(isEnabled); // false
console.log(limit); // 0
console.log(label); // ""
console.log(selectedId); // null
console.log(fallbackValue); // "used"
This behavior is helpful because those “falsy” values may be meaningful application data. A user may intentionally set a limit to 0 or clear a text field to "".
Objects: extract values by property name
Object destructuring uses curly braces. Unlike arrays, property order does not matter. The names in the pattern must match the object’s property keys.
const currentUser = {
id: "u104",
name: "Ravi",
role: "admin",
isVerified: true
};
const { name, role } = currentUser;
console.log(name); // "Ravi"
console.log(role); // "admin"
Even if the object was created in a different order, this behaves the same:
const { role, name } = currentUser;
This is one reason object destructuring fits JSON responses well. API objects usually have named fields, and you want to make your code depend on those names rather than incidental property order.
Rename a property while extracting it
Often, an API field name is not a good local variable name. MongoDB’s _id is a common example. Use a colon to map a source property to the local variable you want:
const apiUser = {
_id: "u104",
name: "Ravi",
role: "admin"
};
const { _id: userId, name, role } = apiUser;
console.log(userId); // "u104"
Read this pattern carefully:
const { _id: userId } = apiUser;
_idis the property to look up onapiUser.userIdis the variable being declared.
Afterward, _id is not a variable in the current scope. The available variable is userId.
Defaults in objects
Defaults work in object patterns too:
const profile = {
name: "Ravi",
role: "admin"
};
const {
name,
role,
avatarUrl = "/images/default-avatar.png"
} = profile;
console.log(avatarUrl); // "/images/default-avatar.png"
You can rename and default in the same pattern:
const {
_id: userId,
avatar_url: avatarUrl = "/images/default-avatar.png"
} = {
_id: "u104"
};
console.log(userId); // "u104"
console.log(avatarUrl); // "/images/default-avatar.png"
The syntax is:
const { sourceProperty: localVariable = defaultValue } = object;
Read the relevant parts of javascript.info’s “Destructuring assignment” to consolidate the syntax and see its complete progression from arrays to objects and function parameters.
Begin in the “Array destructuring” section. Read the initial example, then use skipping positions as a guide to the comma placeholder pattern. Continue through the “Default values” subsection; its key motivation is captured in missing values. Next, read the “Object destructuring” section through the examples of property renaming and defaults. Focus on object matching: object order is irrelevant, but property names are not. Then read “Nested destructuring” and “Smart function parameters.” In the nested section, follow the mirrored pattern. In the final section, first understand why an options object can make a function easier to call by reading the design problem, then study the parameter examples through the end of the section.
Nested data: mirror only the structure you need
Full-stack data is frequently nested. A user document may contain a profile object; an API response may contain a data object that contains a resource. Destructuring can follow that shape.
const user = {
id: "u104",
name: "Ravi",
profile: {
city: "Pune",
skills: ["React", "Node.js"]
}
};
const {
name,
profile: {
city,
skills
}
} = user;
console.log(name); // "Ravi"
console.log(city); // "Pune"
console.log(skills); // ["React", "Node.js"]
Notice what variables were created: name, city, and skills.
There is no profile variable in this example, because the pattern immediately unpacked its contents. If you need the whole nested object and selected fields from it, do that in two deliberate steps:
const { profile } = user;
const { city } = profile;
This is sometimes easier to read than a deeply nested one-line pattern.
A practical caution about nested destructuring
Nested destructuring assumes every parent object exists.
const { profile: { city } } = user;
This requires user.profile to be an object. If profile might be missing or null, the code throws an error before it can bind city.
For reliable application code:
- destructure deeply when the data contract guarantees the nested object;
- validate or normalize uncertain API data before relying on its shape;
- avoid creating one huge destructuring pattern merely because JavaScript permits it.
Readable code is more valuable than compact code.
Destructuring function arguments
A function often receives a large object but needs only two or three fields. Rather than accepting a generic object and repeatedly writing user.name, destructure at the parameter boundary:
function formatUserLabel({ name, role = "member" }) {
return `${name} (${role})`;
}
const user = {
id: "u104",
name: "Ravi",
role: "admin",
createdAt: "2026-03-01"
};
console.log(formatUserLabel(user)); // "Ravi (admin)"
This signature communicates the function’s actual dependency: it needs name, and optionally role. It does not need id or createdAt.
You will see this form repeatedly in React:
function UserBadge({ name, role }) {
return `${name} — ${role}`;
}
At this point, treat it as plain JavaScript. Later, React props will make this pattern routine.
One subtle point: the function receives one object argument, not two positional arguments. This call is correct:
formatUserLabel({ name: "Ravi", role: "admin" });
This call is not:
formatUserLabel("Ravi", "admin");
If a function should safely support being called with no argument at all, give the whole parameter a default empty object:
function formatUserLabel({ name = "Guest", role = "member" } = {}) {
return `${name} (${role})`;
}
console.log(formatUserLabel()); // "Guest (member)"
The outer = {} handles a missing argument; the inner defaults handle missing properties.
A short implementation pass
Create a file such as destructuring-practice.js, run it with Node, or use the browser console. Build the code in these small steps rather than pasting the final result at once.
First, unpack a URL-like string that has been split into an array:
const [resource, productId] = "products/p42".split("/");
console.log(resource); // "products"
console.log(productId); // "p42"
Next, simulate a small API user payload and choose clear local names:
const apiUser = {
_id: "u104",
name: "Ravi",
profile: {
city: "Pune"
}
};
const {
_id: userId,
name,
profile: { city },
avatarUrl = "/images/default-avatar.png"
} = apiUser;
console.log(userId);
console.log(name);
console.log(city);
console.log(avatarUrl);
Finally, turn that extraction into a focused function:
function createWelcomeMessage({ name, profile: { city } }) {
return `Welcome, ${name} from ${city}.`;
}
console.log(createWelcomeMessage(apiUser));
As you inspect each result, apply this quick diagnostic rule:
| If the source is... | Use this pattern | Values are selected by... |
|---|---|---|
| An array | const [first, second] = values | Position |
| An object | const { name, role } = user | Property name |
| A nested object | const { profile: { city } } = user | Matching nested shape |
| A function argument object | function fn({ name }) | Property name at the function boundary |
Key takeaways
Destructuring is a concise assignment pattern for extracting values without modifying the original array or object.
- Use
[]for arrays and other iterables; bindings follow element position. - Use
{}for objects; bindings match property names regardless of property order. - Use commas to skip unwanted array positions.
- Use
property: variableNameto rename an extracted object property. - Use
= defaultValuewhen a missing orundefinedvalue should have a fallback. - Mirror nested structure only when the parent data is reliably present.
- Destructure object parameters when a function needs a limited, named subset of an object.
Next, you will build on the same ... syntax in a different role: spread and rest. That lesson will focus on creating updated arrays and objects without mutation, a core habit for React state and predictable server-side code.
Can't find a good explanation? Sign up and we'll make it for you
Sign up