Explain it simply
Explain it simply
Picture a box full of things. Instead of reaching in one item at a time with box.name, box.role and box.city, you say once: "hand me the name and the role from this box". That one-step unpacking is destructuring.
For objects you choose values by property name; for arrays you choose them by position in the line. Nothing new is computed: existing values are simply copied into variables with short names. The result is shorter code, and the top of a function shows exactly which parts of the data it really uses.
Problem → Why → Solution
The problem: long access chains and misordered arguments
When an order comes back from an API, you end up writing a long path such as response.data.order.customer.name in four or five places. It is hard to read, and when the shape changes you have to fix every copy.
Functions with many options are worse. In a call like createUser("Ana", undefined, undefined, true), nobody reading the call site knows what true means. If one argument slips into the wrong position, no error appears; the code simply builds the wrong user.
function createUser(name, role, city, isAdmin) {
return { name, role: role || "viewer", city, isAdmin };
}
// What do undefined, undefined, true mean here?
const ana = createUser("Ana", undefined, undefined, true);
const order = response.data.order;
console.log(order.customer.name, order.customer.email);
console.log(order.items[0].title, order.items[1].title);Why does this happen?
Positional arguments remember only their order, not their meaning, so the call site loses the information. If the function accepts an options object and destructures it, callers write createUser({ name: "Ana", isAdmin: true }): every value is labelled and the order no longer matters.
Core concept: a pattern on the left, data on the right
In destructuring, the left side of = looks like an object or array literal, but it builds nothing: it is a pattern. JavaScript matches the data on the right against that pattern and copies the matching values into variables. The two kinds of pattern follow different rules.
| Object pattern { } | Array pattern [ ] | |
|---|---|---|
| Matches by | Property name | Position |
| Renaming | { name: displayName } | Any name you like |
| Skipping | Just leave it out | An empty slot: [a, , c] |
| Rest | { a, ...rest } gives an object | [a, ...rest] gives an array |
A default (= "free") is used only when the property is missing or its value is undefined. null, 0 and "" count as real values, so the default is skipped. To cover null as well, destructure first and then write city ?? "Unknown".
Patterns can nest. const { customer: { email } } = order reaches into customer and takes email. But if customer itself is missing, JavaScript tries to read email from undefined and throws a TypeError. Giving the nested level its own default, { customer: { email } = {} }, makes that safe.
One last rule is about assignment. Destructuring into existing variables without const or let needs parentheses for object patterns: ({ a, b } = obj);. Without them, the { at the start of the line is read as a block.
How deep does destructuring copy?
What lands in your variables is a copy of each value. For primitives such as numbers and strings, changing the new variable never touches the original object. When a property holds an array or object, though, only the reference is copied: after const { tags } = post, calling tags.push("new") changes post.tags as well. An object gathered with ...rest is likewise only a shallow copy.
- The left side is a stencil
- Objects match names, arrays positions
- Defaults fill only undefined holes
- ...rest scoops up what is left
The stencil never changes the data; it only copies values out. Reassigning a destructured primitive does not touch the original object.
General pattern
const { propA, propB: newName, propC = fallback, ...restObj } = someObject;
const [itemA, , itemC = fallback, ...restArr] = someArray;
({ propA, propB } = someObject); // assigning to existing variables
function fn({ optionA, optionB = fallback } = {}) {
// use optionA and optionB here
}Object patterns pick by name and array patterns by position. propB: newName renames, = fallback sets a default, and ...rest collects the remainder. The = {} on the parameter lets callers omit the argument entirely.
Run object, array and parameter destructuring
The code below destructures one user object and one array of scores in six different ways. Notice that city holds null. There is a default of "Unknown" for it, so predict what the third output line will be before you run it.
// Object destructuring: pick properties by name
const user = { id: 7, name: "Mya", role: "editor", city: null };
const { name, role } = user;
console.log(name, role);
// Rename a property and give a default for a missing one
const { name: displayName, plan = "free" } = user;
console.log(displayName, plan);
// Defaults replace undefined only, never null
const { city = "Unknown" } = user;
console.log(city);
// Array destructuring: pick values by position, collect the rest
const scores = [92, 85, 78, 64];
const [first, second, ...others] = scores;
console.log(first, second, others);
// Swap two variables without a temporary one
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);
// Destructure an options object right in the parameter list
function formatUser({ name, role = "viewer" }) {
return `${name} (${role})`;
}
console.log(formatUser({ name: "Ko Ko" }));Code breakdown
- Pick by name
const { name, role } = user;Copies user.name and user.role into two variables with the same names; id and city are simply ignored.
- Rename and default
const { name: displayName, plan = "free" } = user;name: displayName means "put the name property into a variable called displayName". user has no plan, so the default "free" is used.
- null is not undefined
const { city = "Unknown" } = user;city exists and holds null, so the default is skipped and the output is null, not "Unknown".
- Position plus rest
const [first, second, ...others] = scores;The first two values go into first and second; the remaining 78 and 64 are gathered into a new array called others.
- Swap in one line
[a, b] = [b, a];The right side builds a new array [2, 1] first, then the pattern on the left unpacks it, so the values swap without a temporary variable.
- Destructured parameter
function formatUser({ name, role = "viewer" }) {The function receives one object and unpacks it right in the parameter list. role was not passed, so "viewer" is used.
Mya editor
Mya free
null
92 85 [ 78, 64 ]
2 1
Ko Ko (viewer)Nested patterns and safe defaults
API responses are usually nested. You can write a pattern that mirrors that shape, but at every level ask: what if this part is missing? The code below protects against both an order without a customer and a call with no argument at all, using = {} defaults.
function describeOrder({ id, customer: { name = "guest" } = {}, items = [] } = {}) {
return `#${id ?? "?"} for ${name}, ${items.length} item(s)`;
}
console.log(describeOrder({ id: 12, customer: { name: "Mya" }, items: ["pen"] }));
console.log(describeOrder({ id: 13 }));
console.log(describeOrder());Do not nest patterns too deeply
A single pattern more than two or three levels deep is hard to read, and the error message will not tell you which level broke. Destructuring one or two levels and reading the rest with optional chaining (?.) is often clearer.
In real projects
In real projects
You see destructuring most in code that handles API data. One line such as const { id, title, author = "Anonymous", ...meta } = post extracts the fields you need, supplies a default for a missing author, and gathers every other field into a meta object. After a fetch, const { data, error } = await res.json() is an everyday sight.
It matters for function design too. Functions with more than three or four options, such as fetchUsers({ page = 1, limit = 20, sort = "name" } = {}), usually take an options object. Callers pass only the options they care about, by name, and adding a new option later does not break any existing call.
In React, function components destructure their props in the parameter list, ({ title, onClose }), and const [count, setCount] = useState(0) is array destructuring. Looping with for (const [key, value] of Object.entries(obj)) uses the same syntax.
Common mistakes
Common mistakes
Expecting a default to replace null
If the database returns city: null, const { city = "Unknown" } = row still gives you null, and the UI may display the text "null". To cover both null and undefined, use const city = row.city ?? "Unknown".
Forgetting = {} on a parameter pattern
Calling formatUser() with no argument on function formatUser({ name }) throws "Cannot destructure property 'name' of 'undefined'". Give every options-object parameter a fallback: ({ name } = {}).
Ignoring a missing nested parent
With const { profile: { email } } = user, a user without a profile crashes the program with a TypeError. Add = {} at the parent level, or read it as user.profile?.email.
Missing parentheses in an assignment
After let a, b;, writing { a, b } = obj; is a SyntaxError because a line starting with { is a block. Write ({ a, b } = obj); and make sure the previous line ends with a semicolon.
Mini challenge
Turn an API order into a summary
Write summarizeOrder(), which takes an order object from an API and returns a one-line summary. Do the destructuring in the parameter list and give defaults for any fields that might be missing.
- Take id and rename customer.name to buyer ("guest" when customer is missing)
- Take the first item as firstItem and the others with ...rest (items defaults to [])
- Collect the remaining top-level fields into ...extra and report how many there are
- summarizeOrder() with no argument at all must not throw
// TODO: destructure id, customer.name (as buyer), items and ...extra here,
// with defaults so that summarizeOrder() works with no argument.
function summarizeOrder(/* pattern goes here */) {
// TODO: split items into firstItem and ...rest
// TODO: return "Order #ID by BUYER: FIRST (+N more), K extra field(s)"
// or "Order #ID by BUYER: no items, K extra field(s)"
}
console.log(summarizeOrder({
id: 41,
customer: { name: "Mya", email: "mya@example.com" },
items: ["keyboard", "mouse", "cable"],
paid: true,
coupon: "WELCOME",
}));
console.log(summarizeOrder({ id: 42, items: [] }));
console.log(summarizeOrder());Expected: Three lines: Order #41 by Mya: keyboard (+2 more), 2 extra field(s); Order #42 by guest: no items, 0 extra field(s); and Order #? by guest: no items, 0 extra field(s).
Show hint
Use a two-level default such as customer: { name: buyer = "guest" } = {}. Take items in the parameter list, then split it inside the body with const [firstItem, ...rest] = items.
Show solution
function summarizeOrder({
id = "?",
customer: { name: buyer = "guest" } = {},
items = [],
...extra
} = {}) {
const [firstItem, ...rest] = items;
const extraCount = Object.keys(extra).length;
const what = firstItem === undefined
? "no items"
: `${firstItem} (+${rest.length} more)`;
return `Order #${id} by ${buyer}: ${what}, ${extraCount} extra field(s)`;
}
console.log(summarizeOrder({
id: 41,
customer: { name: "Mya", email: "mya@example.com" },
items: ["keyboard", "mouse", "cable"],
paid: true,
coupon: "WELCOME",
}));
console.log(summarizeOrder({ id: 42, items: [] }));
console.log(summarizeOrder());Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Object patterns match property names; array patterns match positions
- Rename with prop: newName and set a default with = value
- Defaults apply to undefined only; use ?? when null must be covered too
- ...rest gives a new object from an object pattern and a new array from an array pattern
- Write options parameters as ({ ... } = {}) and protect every nested level
MDN — JavaScript Guide — MDN Web Docs