Edit This isn't a question of whether or not the ternary operator is harmful. It's about whether or not there's a consensus about whether or not it should be used outside of assignment statements. /Edit
Based on a boolean, I want to call one of two different functions (with no return value). I wrote this bit of javascript:
(condition) ? doThis(arg) : doThat(arg)
Which I think looks cleaner than writing out an if-else statement:
if(condition) {
doThis(arg);
}
else {
doThat(arg);
}
My colleagues strongly believe ternary statements should only be used in assignment statements. I can't find style guides that discuss this, probably because languages like Java and C# don't allow this at all (their compilers require ternary operators to return a value). Should this be considered a bad use of the ternary statement? Why?
Best Answer
Generally speaking, the conditional operator is intended to make an if statement with a value.
w = x ? y : z
. Thus, if you're using it for side effects, it's counter-intuitive. Valid, but counter-intuitive; and remember that you're writing code for your teammates to read.