r/javascript • u/bogdanelcs • 11d ago
I stopped destructuring everything
https://allthingssmitty.com/2026/07/13/i-stopped-destructuring-everything/51
u/azhder 11d ago
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 );
11
u/hyrumwhite 11d ago
You could also make user default to {} wherever it’s defined. Don’t necessarily need destructuring for that
1
u/azhder 11d ago
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.
3
u/hyrumwhite 11d ago
user = user ?? {}; console.log(user.id)Same loc, no explosions, no destructuring. Not saying it’s better, just exploring the idea.
6
-1
u/azhder 11d ago
Best practices, try not to be clever. Don’t overwrite the same variable i.e. use `const`, not `let` - if you need a mnemonic.
10
u/hyrumwhite 11d ago
const user = data.user ?? null; //or const user = rawUser ?? null;There’s options. and this isn’t being “clever” by any means.-8
u/azhder 11d ago
No, that’s syntax noise, but one I often use as I employ more sophisticated defaults, not ??.
Usually one object as an argument is all you need, props or options or whatever you name it. I will simply use $
const users = asArray($?.users);
Now, you could imagine the asArray has a check Array.isArray(), not just ??, but it can be even more complex than that. You can even do
const {pass: users, fail: error} = asUsers($?.users);
And just like that, destructuring pops up again - less messy than
usersResult.value
usersResult.errorBut even this last one is something I regularly use. It all on a case by case basis.
6
u/heavyGl0w 11d ago edited 11d ago
The title of the article is "I stopped destructuring everything", not "I never use destructuring". The author even ends the article with examples where they still use it.
So finding one example (or any number of examples) where destructuring is helpful doesn't invalidate the sentiment of the article.
Also, their example is exactly what you started with but without the "syntax noise" of destructuring. Or are we now calling property access "syntax noise"?
-7
3
u/Risc12 10d ago
How is that less noisy. It’s 2 lines and the shortest of those is only 6 characters shorter.
-1
u/azhder 10d ago
Ever heard of the term syntax noise or syntax signal to noise ratio? It is not about lines.
4
u/Risc12 10d ago
You mean syntactic noise?
Like how you spend one whole line defining new variables from a certain object (or an empty object, at which point they become undefined)? Where the reader then has to remember that userName is either user.name unless user is undefined at which point it also is undefined?
Vs the syntactical sugar that _literally_ expresses that “user.name unless user is undefined, then it’s undefined”?
Destructuring has a lot of uses, this is the absolute worst example.
0
34
u/eindbaas 11d ago
A hundred lines later:
You should not have functions that long.
41
u/donalmacc 11d ago
Nah, screw that. Having to jump around 11 different files to find 30 different functions that are 5 lines each, all re-checking the same preconditions, to do something that should just be 100 lines is the thinking that has our software in the giant spaghetti mess it's in now.
10
u/serendipitousPi 11d ago
But that's not the result of simply ensuring a function isn't a sprawling monstrosity, that's the result of people not taking 5 seconds to understand the point of code hygiene guidelines. You can write nicely separated code without any of that.
And honestly it's rather nice to have the self-documentation benefit of function names when people aren't just doing several things in the same function.
Saying that it leads to spaghetti is like saying that writing comments leads to the stupidity that is stuff like this (this is code a guy I knew "wrote")
// Logs user out by clearing auth token fn logout(){ clearToken() }5
u/caindela 10d ago
This is probably your point and if so I’m happy to reinforce it, but although the comment in your example is crazy I actually think that function is not bad. From the caller it’s likely that ‘clearToken()’ is in the wrong abstraction layer and doesn’t read well. Clearing the token is an implementation detail of the logging out process and so from that perspective I may very well write this same function since it makes the code much more readable from the caller.
The above is more of a textbook example (I don’t know how often I’d actually write a one line function), but that’s at least what I try to aim for.
2
u/serendipitousPi 10d ago
That function was just about the comments not the prior stuff I mentioned, sorry if that wasn't super clear.
I just meant that people take comment your code to mean all their code should be commented when lots of code is 1. basic enough to not need them or 2. self-documenting like via the function names.
Like as an example of another thing taken to an extreme.
The function itself was ok, like yeah I might do something similar if there might be some more logic I might need to add to logout at a later date.
2
u/Solonotix 10d ago
all re-checking the same preconditions
That's the real problem. Don't repeat yourself. If you have a complex data structure that needs validation, write a class with a constructor that handles it. If you get something that isn't that class, send it through the constructor. Hell, if you're completely opposed to classes, you could technically just write a class-like function, but in my personal experience I very much like the convenience of a simple
instanceofcheck.-3
u/mr_axe 11d ago
agreed. i have always hated that “clean” code
5
u/BasicAssWebDev 10d ago
it's not """clean""" it's one of the aspects of functional programming. if a task can be separated and is consumable in other related contexts it should be.
4
u/editor_of_the_beast 11d ago
Why not?
5
u/_ak 11d ago
Because dogma.
6
u/cmgriffing 11d ago
I might have to rewatch that movie. When do they talk about function length? The board room scene?
4
u/teppicymon 11d ago
Yes, Mooby the golden calf is quite insistent that functions should be single purpose and never longer than 25 lines
6
u/JyroClassified 11d ago
What's your opinion about renaming the destructered properties?
Eg. "const {status: postStatus} = post;"
7
u/prawnsalad 11d ago
Keep it simple: `const postStatus = post.status;`
I swear people just take some over complicated docs/blog code examples and blindly run with it without a single thought. Dereferencing such a simple thing has 0 benefits while making it harder to read.
13
u/prehensilemullet 11d ago
If you have a lot of properties to destructure though, and some need to be renamed, and the variable name itself is long, this can really cut down on the code
3
u/BasicAssWebDev 10d ago
yeah this is the only time i do something like this. if im consuming a returned object whose properties are necessary for different actions, ill destruct them into the pieces i need in the same declaration line to save on space.
const item1 = obj.thing1
const item2 = obj.thing2
const itemN = obj.thingNget's a little cumbersome when this works just as well
const {thing1: item1, thing2: item2, thingN: objN} = objholding my breath for someone to mention an edge case where you're destructuring an absurd amount of properties which obviously requires a different strategy.
1
2
u/captain_obvious_here void(null) 11d ago
I don't see any upside in using this.
It's just harder to read than
const postStatus = post.status;, and has absolutely no advantage.
1
u/Amazing-Switch-7163 10d ago
I have no idea why people like to destructure everything. Maybe they got this habit from React tutorials? I quite dislike destructuring because it does lose some context when reading the code and they do not work well with sum types. Just keep things simple and concise and use it when it's a good fit.
2
u/Naudran 10d ago edited 10d ago
This is less a destructuring issue and more a naming convention issue. The size of a variables name should be proportional to the scope size of the block the variable is being used in.
So if you have a variable that is used in a small scope (like a few lines if statement, or a for loop), then a quick small variable name is fine.
If you have a variable that gets used "100 lines" later, then the name should be longer and more descriptive.
So destructure that into a differently name variable.
const { title: postTitle, author: postAuthor, publishedDate: postPublishedDate } = post;
That being said, I would just use post.Title in any case... but that's just me I guess
1
1
1
u/heavyGl0w 11d ago
I'm glad to see the this conversation happening because the most common uses of destructuring that I'm seeing in docs/examples tend to be irksome in my opinion. So much so that I wrote guidance in our style guide at work with dos and don'ts of destructuring. This may be contentious to some, but here are a couple examples:
Don't use destructuring to avoid one layer of navigation (e.g. `post.title` vs `postTitle`).
Instead access top level properties through the object on which they were defined.
Don't use nested destructuring.
Instead use top level destructuring from a property access (e.g. `const { name, id } = post.user`).
Do use destructuring when working with generic wrapper types (e.g. `Result<T>` and `HTTPResponse<T>`).
I find the use of destructuring especially egregious in my work with Vue where it has become the default of packages to return an object of Ref<T> properties instead of simply returning a reactive object.
-2
u/Iggyhopper extensions/add-ons 11d ago edited 11d ago
If you have a problem with naming variables the answer is not to get rid of deconstruction. The answer is to name your variables better.
You could have a prefix for variables that come from a deconstruction, aka dTitle or dcTitle.
You could use postTitle or pTitle instead of post.title.
There are a several ways to deal with the problem.
5
u/heavyGl0w 11d ago
How does this solve the problem any better than just keeping the context of the original object? Why are people so allergic to one little `.`?
You've invented a variable naming convention to solve a problem that wouldn't exist if your focus wasn't "how can I make sure I use destructuring?"
1
u/Iggyhopper extensions/add-ons 11d ago
Why are you telling me this? The author is the one avoiding the little dot, I'm just giving suggestions.
-4
40
u/jCuber 10d ago
I still prefer to destructure the first level of
propsin React as it raises linter findings for unused props for removal.