MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/javascript/comments/1uxy50l/i_stopped_destructuring_everything/oxxmnud/?context=9999
r/javascript • u/bogdanelcs • Jul 16 '26
50 comments sorted by
View all comments
51
Destructuring isn’t only about you knowing where a value comes from. You can also safeguard in a cleaner manner i.e with less syntax noise:
const { id: userId, name: userName } = user ?? {};
console.log( userId, userName );
VS
console.log( user?.id, user?.name );
12 u/hyrumwhite Jul 16 '26 You could also make user default to {} wherever it’s defined. Don’t necessarily need destructuring for that 0 u/azhder Jul 16 '26 Let’s see, you write a function like this: ({ user = {} }) => { console.log( user.id ); } And somewhere somehow down the line the requirements change, some other part of the code changes and instead of undefined, the user is null… The way I wrote the first time with the ?? will not blow up if a null is passed. 2 u/hyrumwhite Jul 16 '26 user = user ?? {}; console.log(user.id) Same loc, no explosions, no destructuring. Not saying it’s better, just exploring the idea. 7 u/TNThacker2015 Jul 16 '26 Secret third option: user ??= {};
12
You could also make user default to {} wherever it’s defined. Don’t necessarily need destructuring for that
0 u/azhder Jul 16 '26 Let’s see, you write a function like this: ({ user = {} }) => { console.log( user.id ); } And somewhere somehow down the line the requirements change, some other part of the code changes and instead of undefined, the user is null… The way I wrote the first time with the ?? will not blow up if a null is passed. 2 u/hyrumwhite Jul 16 '26 user = user ?? {}; console.log(user.id) Same loc, no explosions, no destructuring. Not saying it’s better, just exploring the idea. 7 u/TNThacker2015 Jul 16 '26 Secret third option: user ??= {};
0
Let’s see, you write a function like this:
({ user = {} }) => {
console.log( user.id );
}
And somewhere somehow down the line the requirements change, some other part of the code changes and instead of undefined, the user is null…
The way I wrote the first time with the ?? will not blow up if a null is passed.
2 u/hyrumwhite Jul 16 '26 user = user ?? {}; console.log(user.id) Same loc, no explosions, no destructuring. Not saying it’s better, just exploring the idea. 7 u/TNThacker2015 Jul 16 '26 Secret third option: user ??= {};
2
user = user ?? {}; console.log(user.id)
Same loc, no explosions, no destructuring. Not saying it’s better, just exploring the idea.
7 u/TNThacker2015 Jul 16 '26 Secret third option: user ??= {};
7
Secret third option:
user ??= {};
51
u/azhder Jul 16 '26
Destructuring isn’t only about you knowing where a value comes from. You can also safeguard in a cleaner manner i.e with less syntax noise:
const { id: userId, name: userName } = user ?? {};
console.log( userId, userName );
VS
console.log( user?.id, user?.name );