0

In what cases I should use ternary operators instead if/else conditioning?

I was taking into account that many guys use ternary operators. Are there some basic rules for usage?

25th Apr 2018, 11:48 AM
FabricioM
FabricioM - avatar
3 Réponses
+ 2
I think the ternary operator is helpful when you only have a single thing to do for your if and a single thing to do for your else. By using the ternary operator instead of the regular if/else in that case you reduce the number of lines and you make it all more straightforward
25th Apr 2018, 12:06 PM
cyk
cyk - avatar
+ 2
Don't nest it. Don't do complex logic with it. Don't do (cond) ? foo : false or (cond) ? true : foo.
25th Apr 2018, 12:26 PM
Timon Paßlick
+ 1
I don’t know of any basic guidelines for ternary operator use. I use them a lot when trying to get data from the server side to the front end. In the code bases I’ve worked with ternaries tend to get used when setting up some defaults based on some conditional. I know you can have really complicated ternaries (nesting) but that is pretty good way of ticking off your fellow devs
25th Apr 2018, 12:30 PM
Stuart Adams
Stuart Adams - avatar