Every so often thought-pieces will go around proclaiming that you are writing code the wrong way and that you should be writing your code this way instead.
One such opinion I have seen (and will not link because this isn’t a takedown) is recommending the use of Ternary Operators in Javascript over if statements.
While ternaries can make your code look cleaner in some cases by replacing multi-line if statements with one-liners, there are instances where they fall apart quite quickly. Ternary operators exist in all programming languages and the problems they can introduce into a codebase are universal.
Ternaries are hard to read
Sure, they might look cleaner, but ternaries can needlessly make code hard to read. This is the problem I have with “clever coding” and some developers pursuit to write the most convoluted code in an attempt to condense things.
const canAccess = user.isAdmin || user.isEditor || user.level > 6 ? true : false;
It’s a simple one-liner, but there is a lot going on here. Replaced with an if statement, things get a little easier to read.
let canAccess = false; if (user.isAdmin || user.isEditor || user.level > 6) { canAccess = true; }
Understandably, this is an exaggerated example and even so, there is room for improvement here. But, my eyes are instantly drawn to the if statement, it is easier to read and if I need to change it, it will be easier to change as well.
Ternaries fail at dealing with complex conditions
The above example is quite a simple set of conditional checks, but what happens in a situation where things are more complex? A good example is detecting keycodes on the keydown
event in Javascript and reacting accordingly.
While in simple use-cases it is more than fine to use a ternary, complex scenarios with multiple conditions should be avoided like the plague. If you need to check multiple values or check multiple expressions, a ternary condition will be a nightmare.
const prevNext = (e.keyCode == 38) ? 'prev' : (e.keyCode == 40) : 'next' : null;
This is a relatively tame example of multiple expressions, can you imagine throwing more into the mix?
Ternaries are hard to debug
If you have a one-line ternary expression in your application, good luck setting a precise breakpoint. This is where the differences between a ternary statement and if statement is truly highlighted. Sure, you could use a console.log
if you wanted to debug, but setting a breakpoint is not going to be possible.
Code that is broken up into multiple lines might not look as appealing as a condensed ternary condition, but at least you can set a breakpoint and go through it line-by-line to debug the flow.
I am not saying that you shouldn’t use ternaries, because they have a purpose. But to go as far as recommending their use over if statements in general defies all common sense.