0

Righto, so I have come across this in a lot of code that I have read and I understand the functional role of the conditional operator in Javascript; what I do not understand is when one should use it.

I have read the ECMAScript Specification 5.1 on it, but it doesn't help me a great deal in deciding when to impliment it.

For example, I can quite easily see the benefit of replacing the code:

if (isTrue == true) {
  doSomething();
}
else {
  doSomethingElse();
}

With next:

isTrue ? doSomething() : doSomethingElse()

Where I fall down is when either the code inside the if... else... statement is lengthy or the conditional operator is nested inside (an)other conditional operator(s). The obvious candidate for deciding when to use which version of the conditional statement is "does replacing it with the conditional operator make the code easier to follow?". Unfortunately I am rather inexperienced with writing code and I am unsure of when this is and I'm biased by understanding my own code well, no matter how poorly written it may be.

Can anybody with significantly more experience than me give me a slightly less subjective test for when you use it, so that I can attempt to follow suit?

Related: JS How to use the ?: (ternary) operator

Community
  • 1
  • 1
  • 4
    You *can* use it for statements, but I'd leave that to the minifiers. I only use it in expressions. – Joe White Apr 01 '15 at 16:38
  • 2
    There's really not more to this than "use the coding technique that makes your code the clearest, cleanest and easiest to understand and maintain". Sometimes the ternary operator makes things cleaner and sometimes it just makes things harder to read. Part of becoming a more experienced programmer is recognizing when code is not clear and improving it by using a different technique and knowing which technique to choose when you first write the code. – jfriend00 Apr 01 '15 at 17:07

2 Answers2

3

I think it is useful for code legibility and simplicity in attributions. Which one is easier to read? :)

var numberType = (number % 2 == 0) ? "even" : "odd";

// or

var numberType;
if (number % 2 == 0) {
    numberType = "even";
} else {
    numberType = "odd";
}
Bruno Toffolo
  • 1,504
  • 19
  • 24
1

Ternary operator was designed to replace

if (test) {
 i = something();
} else {
 i = somethingElse();
}

with

i = test?something():somethingElse();

You can't see it as an if-then-else shortcut, but really as a conditional expression (not conditional instruction).

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69