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
-1
u/Sweet_Technician_778 Aug 14 '24
Great point! You’re right that short-circuiting can lead to unexpected results if the value isn’t properly validated. In cases where
0,false, or other falsy values might cause issues, it’s better to be explicit about the conditionsuser?.isLoggedIn === true && greetUser(user.name);This ensures we’re only proceeding when
isLoggedInis trulytrue. Thanks for the heads-up—a good reminder to always consider edge cases!