DEV Community

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

Posted on

Shorten your if statements using the '&&' operator

Today I learned a pretty cool trick!

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

So instead of using this:

if (iAmHungry) {
  bakeAnEgg()
}
Enter fullscreen mode Exit fullscreen mode

You can use it like this!

iAmHungry && bakeAnEgg()
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

Top comments (8)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

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

iAmHungry? bakeAnEgg() : 0
Collapse
 
toktoktwan profile image
Twan Mulder

Why is it ugly?

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

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

or

if (iAmHungry) bakeAnEgg();
Thread Thread
 
toktoktwan profile image
Twan Mulder

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

Collapse
 
decadef20 profile image
Decade

The first way is much friendly to debugger

Collapse
 
toktoktwan profile image
Twan Mulder

Why?

Collapse
 
crivote profile image
crivote

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

Collapse
 
toktoktwan profile image
Twan Mulder • Edited

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!")