I used to write const everything = response.data and then manually pull out what I needed. Turns out JavaScript destructuring has been doing the heavy lifting I was ignoring for years.
Here are the three patterns I actually use daily, not the clever one-liners that win code golf.
1. Nested Object Destructuring Without the Mess
APIs love nesting. The data you want is always three levels deep. Instead of writing response.data.user.profile.name like a peasant:
const { data: { user: { profile: { name, email } } } } = response;
// name and email are now clean variables
console.log(name); // 'Davide'
console.log(email); // 'whatever@whatever.com'Yes, it looks ugly on one line. But the alternative is three lines of const user = data.user that nobody needs to read.
I rename things when the API gives me terrible keys:
const { user_name: userName, created_at: createdAt } = apiResponse;
// Now I'm not stuck with snake_case in my JavaScript2. Array Destructuring With Defaults and Skips
This one I use constantly with function returns and CSV-like data:
// Skip elements you don't need
const [, , thirdItem] = someArray;
// Defaults for missing values
const [first = 'default', second = 'also default'] = maybeEmptyArray;
// Swap without a temp variable
let a = 1;
let b = 2;
[a, b] = [b, a];
// a = 2, b = 1. Done.The comma syntax for skipping is ugly but useful. I use it mostly when parsing comma-separated values or when some API returns arrays with positional meaning ( which is bad API design, but here we are ).
3. Function Parameter Destructuring
This is the one that changed how I write functions. Instead of:
// Gross positional args
function createUser(name, email, role, active) {
// Was active the 4th or 5th param? Who knows.
}
// Much better
function createUser({ name, email, role = 'user', active = true }) {
// Order doesn't matter, defaults are clear
}
// Call it however you want
createUser({
email: 'test@test.com',
name: 'Davide'
});The object parameter pattern means I never have to remember argument order again. And defaults right in the signature beat defaulting inside the function body every time.
The Rest Operator Counts
One more that comes up a lot:
const { id, ...rest } = userInput;
// Now 'rest' is everything except id
// Perfect for update endpoints where you want to strip the ID
await db.update(id, rest);I use this for separating identifiers from mutable data. Cleaner than manually deleting keys.
Conclusion
Destructuring is not fancy syntax. It is the syntax that makes the rest of your code readable. The nested extraction, the rename, the rest spread — these three patterns cover 90% of what I actually need.
Stop writing const x = obj.a.b.c and start destructuring. Your future self will thank you ( or at least swear slightly less ).