DEV Community

Discussion on: Prevent Object Retrieval TypeError with &&

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Is it just me, or does it feel like the elvis operator will only enable us to be more negligent?
Nothing stops us writing

const d = a?.b?.c?.d
if (d) doStuff(d)

when what we really needed was

const d = a.b?.c.d
if (d) doStuff(d)

Which will make the code not "fail fast", even though there's no correct logic when the a has no b or a present c has no d.

The currently possible code:

const {c} = a.b
if (c) doStuff(c.d)

tells us a lot more about the structure. And it's not a token longer!

The main problem here is that a 3-level destructuring is seen as "showing off" most of the time, and (often correctly) shamed as "unreadable", here one can just say this is "defensive programming". Which it's not, since you are failing to throw valuable errors in the "safe" inner code.

So, I am sure there are genuine uses, I have many places in my code I'd like to use it myself, especially the ?.(). But I fear it will be overused, and its overuse "well-justified".

Collapse
 
samanthaming profile image
Samantha Ming

You’re absolutely right! It’s one of those common JS saying, just because you can doesn’t mean you should. When it’s used appropriately, it’s super helpful. And if you abuse it, it becomes a code smell. Definitely something to be careful of. Thanks for pointing that out 👍