DEV Community


Discussion on: Javascript Tips for Beginners

_garybell profile image
Gary Bell

To make this even better, we can make if, else statements even shorter using the ternary operator.

Can you explain what makes a ternary operator better than an if-else statement?

And nesting them so the else is, itself, an ternary operator is making JavaScript be like the formula bar for Excel - unreadable. If I got a code review where someone had nested ternary operators, I'd fail it on readability and maintainability grounds. If it can't be easily followed by someone new to the code base, it's pointless.

The rest of the article is pretty useful, and reminded me of a couple of things which I haven't used for a while so forgotten about.

terpinmd profile image

By default most linting rules will fail that nested ternary. That is just a terrible pattern. I don't get this current trend with avoiding else stemtements.

stefandurlesteanu profile image
Stefan Durlesteanu

I think that ternary operator is good, but! not the nested one (spaghetti code...).
I usually use it when I whant to assign a value to a variable based on a criteria.

hb profile image
Henry Boisdequin Author

I agree with you. I just wanted to show that you could do an if, else if, and else with a ternary operator.

Thread Thread
_garybell profile image
Gary Bell

Thanks. It looked like you were encouraging people to do it.

I agree that ternary operators have their place, but nesting them in the real world (outside of excel or similar) is just madness