Cover image for Shorten your if statements using the '&&' operator

Shorten your if statements using the '&&' operator

toktoktwan profile image Twan Mulder ・1 min read

Today I learned a pretty cool trick!

You can use the '&&' operator to shorten your if statements.

So instead of using this:

if (iAmHungry) {

You can use it like this!

iAmHungry && bakeAnEgg()

Would you use this in your own code?
How would this impact the readability of your code?

Alt Text


markdown guide

That's very ugly. At the very least use the ternary operator which is at least made for conditionals:

iAmHungry? bakeAnEgg() : 0

&& and || are not meant as control-flow syntax but as operators, so using them for the former will confuse people and just look weird. It aso provides no real benefit when compared to either

iAmHungry? bakeAnEgg() : 0


if (iAmHungry) bakeAnEgg();

Thanks for the detailed response! This is definitely a good case against using '&&' as an operator.


The first way is much friendly to debugger


Because is very limited. How would you add an else clause?


Good question!

If the else clause if very simple, you could use a ternary operator instead.
So something like:

iAmHungry ? bakeAnEgg() : console.log("I'm not hungry!")