Some say that the only reason I like ternary code snippets is that it gives me an opportunity to make the title a “tern” pun.
…
They’re not wrong.
I’m actually a defender of ternaries. Just last week, I wrote this line of C++ code:
ControllerState response = allMotorsIdle() ? READY : NOT_READY;
That's a good use of ternaries, in my opinion. It's a clear translation- if all motors are idle, we're ready, otherwise we're not, keep waiting. Simple, easy to read, and turns what really is one idea (if we're idle, we're ready) into one line of code. Ternaries can make code more clear.
Which brings us to this anonymous submission.
disableEstimateSent: function () {
let surveyCompleted = (modalControl.survey[0].Survey_Complete == undefined || modalControl.survey[0].Survey_Complete == false) ? false : true;
return !surveyCompleted;
}
This is the perfect storm of bad choices. First, we have a long, complex expression in our ternary. I mean, not all that long, it’s only got two clauses, but boy howdy are we digging down the object graph. For the same object. Twice. An object which is either false
or undefined
, which in JavaScript booleans, undefined
is also falsy. So if Survey_Complete
is falsy, we store false
in surveyCompleted
… and then return !surveyCompleted
.
Extra variables, double negatives, ugly ternaries. This is a work of art.
Our anonymous submitter of course went all Banksy and shredded this work of art and replaced it with a more prosaic return !modalControl.survey[0].Survey_Complete
.