Destructuring in JavaScript: Arrays, Objects, Defaults, Renaming and Nested Patterns
Unpack values from arrays and objects in one line: array and object patterns, skipping, rest elements, default values (and why null skips them), renaming, computed keys, nested patterns, swapping, destructuring in loops and function parameters, assignment without declaration, and common errors.
kvi5hnuCode Sprout team member6 min readOn this page
Destructuring lets you pull values out of arrays and objects and into variables with a single, readable statement. Instead of
const name = user.name;
const email = user.email;
const city = user.address.city;
you write
const { name, email, address: { city } } = user;
It arrived in ES2015 and is now everywhere: React hooks (const [count, setCount] = useState(0)), imports, function parameters, loops over Object.entries. This article covers every form, plus the traps.
The idea that makes it easy: the pattern on the left mirrors the shape of the data on the right. Arrays match by position, objects by property name.

Array destructuring
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;
console.log(red, green, blue);
const [first, , third] = [10, 20, 30]; // a hole skips an element
console.log(first, third);
const [a, b] = [1]; // missing elements are undefined
console.log(a, b);
const [winner, ...others] = ["Ana", "Bea", "Cai"]; // rest collects the remainder
console.log(winner, others);
255 128 0
10 30
1 undefined
Ana [ 'Bea', 'Cai' ]
Extra elements on the right are ignored. The rest element ...name must be last, and it always produces a real array (possibly empty).
Any iterable works
Array patterns don't require an array: they consume any iterable (part 12), such as strings, Maps, Sets and generators. They take only as many values as the pattern needs:
const [initial, ...restOfName] = "Zoë";
console.log(initial, restOfName);
const [[firstKey, firstValue]] = new Map([["theme", "dark"], ["lang", "pt"]]);
console.log(firstKey, firstValue);
const [smallest] = new Set([3, 1, 2]); // a Set keeps insertion order
console.log(smallest);
Z [ 'o', 'ë' ]
theme dark
3
Swapping variables
Destructuring assignment swaps values without a temporary variable:
let left = "L", right = "R";
[left, right] = [right, left];
console.log(left, right);
R L
Object destructuring
const user = { id: 7, name: "Ana", email: "ana@example.com", role: "admin" };
const { name, email } = user; // by name: order doesn't matter
console.log(name, email);
const { role: job } = user; // rename: property role → variable job
console.log(job);
const { phone } = user; // missing properties are undefined
console.log(phone);
const { id, ...profile } = user; // rest collects the other own properties
console.log(id, profile);
Ana ana@example.com
admin
undefined
7 { name: 'Ana', email: 'ana@example.com', role: 'admin' }
Reading the rename syntax: in { role: job }, the left side is the property to read and the right side is the variable to create, the same order as in an object literal ({ key: value }). A common mistake is to read it as a type annotation, as in TypeScript; it isn't.
Object patterns work on any value that can have properties, including primitives through their wrappers:
const { length } = "hello";
console.log(length);
const { 0: firstItem, length: count } = ["x", "y", "z"]; // arrays are objects too
console.log(firstItem, count);
const field = "status";
const { [field]: statusValue } = { status: "shipped" }; // computed property name
console.log(statusValue);
5
x 3
shipped
Default values
Both kinds of pattern can give a variable a default, used when the value is undefined:
const [x = 1, y = x * 2] = []; // later defaults can use earlier variables
console.log(x, y);
const { theme = "light", size = 14 } = { theme: "dark" };
console.log(theme, size);
const { level: lvl = 1 } = {}; // rename and default together
console.log(lvl);
const { volume = 50 } = { volume: null }; // null is a real value: no default!
console.log(volume);
1 2
dark 14
1
null
The last case surprises people. Defaults apply only to undefined, never to null (article 18). APIs that return null for missing fields will slip past your defaults; use ?? after destructuring if you need both covered.
Defaults are evaluated lazily, only when needed, so an expensive default (such as a function call) costs nothing when a value is present.
Nested patterns
Patterns can nest to match nested data:
const order = {
id: "A-17",
customer: { name: "Bea", address: { city: "Porto" } },
items: [{ sku: "pen", qty: 3 }, { sku: "ink", qty: 1 }],
};
const {
customer: { name: buyer, address: { city } },
items: [{ sku: firstSku }, ...moreItems],
} = order;
console.log(buyer, city, firstSku, moreItems.length);
Bea Porto pen 1
Note that customer and address are not variables here; they're just paths. Only the names at the leaves (buyer, city, firstSku, moreItems) are created. If you also want the intermediate object, list it separately: const { customer, customer: { name } } = order;.
Deep patterns get hard to read quickly. Two levels is usually the comfortable limit; beyond that, destructure in steps.
Missing nested objects throw
Destructuring undefined or null throws a TypeError, and that includes a missing intermediate object:
const attempts = {
"const { a } = null": () => { const { a } = null; },
"const [b] = undefined": () => { const [b] = undefined; },
"const [c] = {}": () => { const [c] = {}; }, // not iterable
"nested, missing": () => { const { address: { city } } = {}; },
};
for (const [label, run] of Object.entries(attempts)) {
try { run(); } catch (err) { console.log(label.padEnd(22), err.name); }
}
const { address: { city } = {} } = {}; // a default object prevents the error
console.log(city);
const { a } = null TypeError
const [b] = undefined TypeError
const [c] = {} TypeError
nested, missing TypeError
undefined
The = {} default on the intermediate level is the standard defense.
Destructuring in function parameters
This is one of the most useful forms. A function taking an options object can destructure it right in the parameter list, with defaults for every option:
function createButton({ label, color = "blue", size = "medium", disabled = false } = {}) {
return `${label ?? "Button"} [${color}, ${size}${disabled ? ", disabled" : ""}]`;
}
console.log(createButton({ label: "Save", color: "green" }));
console.log(createButton({ label: "Delete", disabled: true }));
console.log(createButton()); // the = {} makes the argument optional
Save [green, medium]
Delete [blue, medium, disabled]
Button [blue, medium]
Benefits over positional parameters: callers name what they pass, the order doesn't matter, options can be skipped, and adding a new option doesn't break existing calls. The trailing = {} is important: without it, calling createButton() would try to destructure undefined and throw.
Arrays work the same way, which is common for pairs:
const distance = ([x1, y1], [x2, y2]) => Math.hypot(x2 - x1, y2 - y1);
console.log(distance([0, 0], [3, 4]));
5
Destructuring in loops
for...of can destructure each element, which pairs perfectly with Object.entries and Map:
const stock = { apples: 4, pears: 0 };
for (const [fruit, count] of Object.entries(stock)) {
console.log(`${fruit}: ${count}`);
}
const people = [{ name: "Ana", langs: ["pt", "en"] }, { name: "Cai", langs: [] }];
for (const { name, langs: [mainLang = "none"] } of people) {
console.log(name, mainLang);
}
apples: 4
pears: 0
Ana pt
Cai none
Assignment without declaration
You can destructure into existing variables (or any assignable target, like object properties or array elements). For object patterns, wrap the whole statement in parentheses, because a line starting with { is parsed as a block:
let width, height;
({ width, height } = { width: 640, height: 480 }); // the parentheses are required
console.log(width, height);
const box = {};
[box.w, box.h] = [10, 20]; // targets can be properties
console.log(box);
640 480
{ w: 10, h: 20 }
If you write semicolon-free code, put a semicolon before the parenthesis (;({ a } = obj)), otherwise it may join the previous line (article 8).
What the rest property copies
An object rest { ...rest } collects own, enumerable properties that weren't named in the pattern, into a new plain object. Inherited properties aren't included, and it's a shallow copy (article 21). This makes it a neat way to omit properties without mutating:
const account = { id: 1, user: "ana", password: "s3cret", token: "abc" };
const { password, token, ...safeToShow } = account;
console.log(safeToShow);
console.log(account.password !== undefined); // the original is untouched
{ id: 1, user: 'ana' }
true
Common questions
Is destructuring slower than normal property access?
Not meaningfully. Engines compile simple object destructuring to the same property reads. Array destructuring uses the iteration protocol, which is optimized for real arrays.
Can I destructure function return values?
Yes, and it's a common way to return several values. Return an array:
function minMax(xs) {
return [Math.min(...xs), Math.max(...xs)];
}
Then destructure it: const [lo, hi] = minMax(data);. Return an object instead when there are more than two values or the order isn't obvious: const { lo, hi } = stats(data).
Why does const { a: { b } } = obj not give me a variable a?
a: in a pattern is a path, saying "go into property a". Only the innermost names become variables. List a separately if you need it: const { a, a: { b } } = obj.
Does destructuring copy objects?
Each variable receives the value of the property: for objects, that's a reference to the same nested object, not a copy. Only rest patterns create new containers, and those are shallow.
Summary
- Array patterns match by position (holes skip,
...restcollects the remainder) and work with any iterable. - Object patterns match by name;
{ prop: newName }renames,[expr]computes the key, and...restcollects remaining own enumerable properties. - Defaults (
= value) apply only toundefined, nevernull, and are evaluated lazily. - Nested patterns follow nested data; destructuring
null/undefinedthrows, so add= {}defaults at uncertain levels. - Destructure options objects in parameters (with
= {}), and[key, value]pairs infor...of. - Assigning to existing variables with an object pattern needs parentheses:
({ a } = obj).
Practice Questions
What are a and b after this code?
const [a = 5, b = 7] = [undefined, null];
Answer
a is 5 (the value was undefined, so the default applies) and b is null (a real value, so no default).
Swap the first and last elements of const arr = [1, 2, 3] with one destructuring assignment.
Answer
[arr[0], arr[2]] = [arr[2], arr[0]];. The right side is evaluated first into a new array, then its values are assigned to the two targets. The array becomes [3, 2, 1].
Given an object shaped like the one below, write a destructuring pattern that extracts city and doesn't throw if profile is missing.
{ profile: { address: { city: "Lima" } } }
Answer
const { profile: { address: { city } = {} } = {} } = data;
Each level that might be missing gets a = {} default.
What does this code produce?
const { length, 0: head } = "hey";
Answer
length is 3 and head is "h". Strings have a length property and index properties like 0.
Why does { x } = point; on its own line fail, and how do you fix it?
Answer
A statement starting with { is parsed as a block, so { x } is a block followed by = point, a syntax error. Wrap the assignment in parentheses: ({ x } = point);.
Review quiz
You've finished Part 3. Check your understanding with the Types, Values and Variables review quiz: 25 questions, most of them "what does this print?", covering numbers, strings, truthiness, null and undefined, symbols, references, conversions, ==, declarations, scope and destructuring.
Previous: Scope in JavaScript: Block, Function, Module and Global Scope and the Temporal Dead Zone
Next: JavaScript Expressions: Primary Expressions, Literals, Initializers and Property Access

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.