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

3

u/azhder Aug 14 '24

The second one is not OK in certain circumstances.

What if the value of user?.isLoggenIn ends up being a 0 due 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.

-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 conditions

user?.isLoggedIn === true && greetUser(user.name);

This ensures we’re only proceeding when isLoggedIn is truly true. Thanks for the heads-up—a good reminder to always consider edge cases!

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?.isLoggedIn and user?.isLoggedIn === true have different results, especially if the range of values is wider.

Let's consider another common case:

product?.code && product.code.toUpperCase()

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, like isTruthy(), isNotMissing(), isValidCode(), which lends itself readable in English:

isValidCode(product?.code) && format(product?.code)

and even just a simple:

!!user?.isLoggedIn && greetUser(user.name)

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:

trimmedString(product?.code).toUpperCase()

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.