JavaScript Destructuring Tricks You Should Know
Advanced destructuring patterns for cleaner, more expressive JavaScript.
Default Values
``js
const { timeout = 5000, retries = 3 } = options;
`
Defaults apply only when the value is undefined, not null.
Rename While Destructuring
`js
const { name: userName, id: userId } = user;
`
Combine with defaults: const { name: userName = 'Anon' } = user;
Nested Destructuring
`js
const { address: { city, zip } } = customer;
`
Throws if address is undefined. Pair with default: const { address: { city } = {} } = customer;
Array Skipping
`js
const [first, , third] = items;
const [head, ...rest] = items;
`
Function Parameter Destructuring
`js
function createUser({ name, email, role = 'user' }) {}
createUser({ email: 'a@b.c', name: 'Ada' });
`
Order-independent named parameters without an options class.
Swap Variables
`js
[a, b] = [b, a];
`
No temporary variable needed.
Pull Values from Promise.all
`js
const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
`
Computed Keys
`js
const key = 'name';
const { [key]: value } = obj;
`
Useful when destructuring a dynamic property.
Iterables Beyond Arrays
`js
const [a, b] = new Set([1, 2, 3]); // 1, 2
const [[k, v]] = new Map([['x', 1]]); // 'x', 1
`
Anything iterable destructures into an array pattern.
Loop Destructuring
`js
for (const { id, name } of users) {}
for (const [key, value] of Object.entries(obj)) {}
``
These two patterns alone make a lot of code disappear. See [array methods cheatsheet](/blog/array-methods-cheatsheet) for more iteration.