Use the Conditional (Ternary) Operator Why?

Tell us what’s happening:

Why should ternary conditional operator be used? I find the conditional “if” more comfortable. Similarly, I would appreciate someone to explain what the differences are, in addition to the syntax and in what other cases it would be useful or more efficient to use the conditional operator (ternary) instead of the conditional “if”.

Thank you.

Your code so far

function checkEqual(a, b) {
  return a == b ? true : false;

console.log(checkEqual(1, 2));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:

it is a shorter way to deal with a if/else situation - for example if a variable would get a value or an other depending on a condition
if you could do it with an if/else but it’s just a simple assignment or a return statement with the ternary operator it is shorter

you don’t need to use it if you are not comfortable with it, but learn it as if you ever found yourself working on already existing code you need to know what it does

Thank you very much. :+1:

please don’t post obscured links - it can be interpreted as spam

1 Like

To get a bit technical, it’s because the ternary operation is an expression that gets evaluated and transformed into a value.

It’s also similar to the following expression:

booleanExpr && exprTrueResult || exprFalseResult

Given that this JS sentence is left-associative: in ((true && "hello") || "world") for example, what happens is that the AND operator forces the leftmost expression to yield a truthy result for the 2nd to be evaluated and then returned as the result of the whole expression; or falsey for the 3rd one to be evaluated and returned.

The ternary operator is similar except you use ? and : and can be used almost everywhere:

return bExpr ? tExpr : fExpr // return statements inside functions
"the lights are" + (toggler ? "on" : "off") // toggling between values based on a condition
const switchedValue = ifBoolean // Switch-like or if-like variable assignment
  ? "val1"
  : elseIfBoolean
    ? "val2"
    : "val3" // else

And many other use cases