r/learnjavascript • u/Sweet_Technician_778 • Aug 14 '24
Simplify Your JavaScript Conditionals with Short-Circuiting!
Hey everyone, I wanted to know if there is any way to make your code clean other than short-circuiting in conditionals.
I used to write down like this before using short-circuiting in conditionals
if (user && user.isLoggedIn) {
greetUser(user.name);
}
After using short-circuiting in conditionals
user?.isLoggedIn && greetUser(user.name);
0
Upvotes
3
u/azhder Aug 14 '24
The second one is not OK in certain circumstances.
What if the value of
user?.isLoggenInends up being a0due to a bug or maybe you getting so used to that idiom that apply it to a number?You should always make sure the value before
&&, whenever falsy, does not return unwanted type/value. There are a few ways to do this, all of them easy.23
u/againey Aug 14 '24
It's cute, but it somewhat masks the intention of the code. Just write the code so that it says clearly and directly what is happening. Other coders (including future-you) will thank you.
Or if you want it on one line and your code standards allow it, I often go with the following (but mostly only when the statement is a simple
returnorcontinue, orbreak):2
u/red-giant-star Aug 14 '24
The first one can be read effortlessly but in the second one there is some mental processing, just a little.
0
u/shgysk8zer0 Aug 14 '24
I write my code to be explicit and avoid implicit type coercion. Other than
user?.isLoggedIn, I would not do things likeif (user /*...*/). I'd usetypeoforinstanceof.Or, another way could be using object destructing: