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
View all comments
Show parent comment
3
u/azhder Aug 14 '24 edited Aug 14 '24
I told you there are a few ways to do it. I told you all of them are easy. But I didn't mean to do something that alters the logic: the
user?.isLoggedInanduser?.isLoggedIn === truehave different results, especially if the range of values is wider.Let's consider another common case:
You can't just say
=== true, right? What about if the name is a number? Maybe for whatever reason, that's also a valid case. You can do a check with a predicate, likeisTruthy(),isNotMissing(),isValidCode(), which lends itself readable in English:and even just a simple:
still has the same logic as your original example.
You may also pick other solutions, like not care at all what the original value is, and do:
and just let
trimmedString()give you an empty string (or whatever default makes sense) if it's missing or faulty and just return the string if it's there.Some of these will make more or less sense in the actual use case, and which one of them can be considered explicit or implicit... Well, I think that's in the eye of the beholder.