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()
}
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?
Top comments (8)
That's very ugly. At the very least use the ternary operator which is at least made for conditionals:
Why is it ugly?
&&
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 eitheror
Thanks for the detailed response! This is definitely a good case against using '&&' as an operator.
The first way is much friendly to debugger
Why?
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: