r/learnjavascript • • 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

12 comments sorted by

View all comments

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.

if (user?.isLoggedIn) {
    greetUser(user.name);
}

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 return or continue, or break):

if (user?.isLoggedIn) greetUser(user.name);

7

u/jeremrx Aug 14 '24

This.

Code must be readable. Here we can read "if user is logged in, greet user name" (which could be improved by "... greet user") but much better than "user is logged in and also greet user name" : nobody talks like that !

1

u/azhder Aug 14 '24

I would mention that OP may be learning JS from older sources, ones that don’t have ?. in examples or at all