DEV Community

Discussion on: Javascript Tips for Beginners

Collapse
 
_garybell profile image
Gary Bell • Edited

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.

Collapse
 
terpinmd profile image
terpinmd

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.

Collapse
 
stefandrl profile image
Stefan Drl

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.

Collapse
 
hb profile image
Henry Boisdequin

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