Destructuring
Syntax that pulls values out of an object or array and assigns them to variables in one statement. The pattern on the left mirrors the shape of the data on the right.
Detailed Explanation
You are reading a nested API response. Before ES6 you wrote const city = response.data.user.address.city; and repeated that line for every field you needed. Destructuring lets you write the shape once and name several pieces at the same time.
There are two forms.
Object destructuring matches by property name. const { id, email } = user declares id and email from the matching properties. Order is irrelevant; names are everything. Rename with a colon: const { id: userId } = user. A missing property gives undefined, exactly like a normal property read.
Array destructuring matches by position. const [first, second] = items takes index 0 and index 1. Skip positions with a bare comma: const [, second] = items. It works on anything iterable, not only arrays, so strings, Sets, Maps and generators all destructure.
Defaults fill gaps. const { retries = 3 } = options uses 3 when retries is missing. The trigger is strict: the default applies only when the value is exactly undefined. A stored null, 0, or "" is a real value and passes through. Defaults are evaluated lazily, so { list = expensive() } calls expensive only when needed, and a later default can reference an earlier binding.
Rest collects the remainder. const { id, ...rest } = user puts every other own enumerable property into a new object. In arrays, const [head, ...tail] = items does the same by position. The rest element must come last. This produces a shallow copy: nested objects are shared, not cloned.
Destructuring composes, which is where it earns its place. Nested patterns reach into deep structures, and function parameters can be destructured directly. A function taking ({ retries = 3, timeout = 1000 } = {}) documents its options in the signature, supplies defaults, and still works when called with no arguments at all. That trailing = {} matters: without it, calling the function with nothing throws, because you cannot destructure undefined.
Two syntax traps. Destructuring an existing variable without const/let needs parentheses — ({ a } = obj) — otherwise the parser reads the leading brace as a block. Swapping variables with [a, b] = [b, a] after a line that lacks a semicolon will be parsed as an index into the previous expression.
The costs are real but small. Array destructuring goes through the full iterator protocol, so it is slower than indexing in a hot loop, and destructuring an infinite generator without a rest element is fine but with one never terminates. Deeply nested patterns are write-once code: const { a: { b: { c } } } = x is hard to scan and throws if any intermediate level is missing. Keep patterns one or two levels deep and let optional chaining handle uncertain paths.
Code Examples
const response = {
status: 200,
data: { user: { id: 7, name: "Ada", tags: ["admin", "beta"] } },
};
// Nested pattern with a rename and a default.
const {
status,
data: {
user: { name, role = "member", tags: [primaryTag] },
},
} = response;
console.log(status, name, role, primaryTag); // => 200 Ada member admin
// Rest gathers the leftovers into a new object (shallow copy).
const { id, ...withoutId } = response.data.user;
console.log(Object.keys(withoutId)); // => [ 'name', 'tags' ]Destructured parameters: named options, defaults, safe when called bare.
// Destructured parameters: named options, defaults, safe when called bare.
function fetchWithRetry(url, { retries = 3, timeout = 1000, signal } = {}) {
// ^ `= {}` lets you
// omit the object
return `${url} r=${retries} t=${timeout} signal=${signal ?? "none"}`;
}
console.log(fetchWithRetry("/api/users")); // => /api/users r=3 t=1000 signal=none
console.log(fetchWithRetry("/api/users", { retries: 0 })); // => /api/users r=0 t=1000 signal=none
// Defaults only fire on `undefined`, never on null or 0.
const { limit = 50 } = { limit: null };
console.log(limit); // => nullCommon Gotchas
You cannot destructure `null` or `undefined`
`const { a } = undefined` throws a `TypeError`. Give the parameter a `= {}` default or check the value first.
Defaults ignore `null`
only `undefined` triggers a default. An API that returns `null` for a missing field will hand you `null`, not your fallback.
Assignment without a declaration needs parentheses
`{ a } = obj` is parsed as a block and is a syntax error. Write `({ a } = obj)`.
Rest is a shallow copy
`const { ...copy } = obj` duplicates the top level only. Nested objects are still shared references.