Ternary Operator

The ternary operator is an operator that takes three arguments. The condition is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. If it helps you can think of the operator as shortened way of writing an if-else statement. It is often used as a way to assign variables based on the result of an comparison. When used correctly it can help increase the readability and reduce the amount of lines in your code.

Here is the syntax -

condition ? "trueExpression" : "falseExpression"

Here is an example -

let age = 40;
let access = age>30?"yes":"no";

In the above example, age>30 is the condition which is a conditional statement in our example. You can use function call that returns a value, or expression what evaluates to a value. Whatever you use here it must evaluate to Boolean value. If not, this operator will try to do a implicit conversion. However, based on the Boolean value of the condition it will determine which one should be returned. If the condition is true, the left operand of the : gets returned. If the condition is false, then the right side operand of the : gets returned. So in the above example, the value of access will be yes.

The above can be done with if else structure as well -

if(age>30){
	access = "yes";
}else{
	access = "no";
}

But the operator approach is more concise.

Nested Ternary Operator

You can also write nested ternary operator like the following -

$variable = ($x==1) ? (($y==2) ? true : false) : false;

For complex expression use parenthesis

If your condition is a complex statement you should wrap them within a parenthisis. Not just condition, but even left and right operand of the : operator should be within parenthesis if they are complex statement to make sure thing works properly.

	(condition) ? (firstOperand) : (secondOperand);

Nested Ternary Operator

The ternary operator can be nested even furture like this -

// js
let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :
  (age < 18) ? 'Hello!' :
  (age < 100) ? 'Greetings!' :
  'What an unusual age!';

alert( message );

It may be difficult at first to grasp what’s going on. But after a closer look we can see that it’s just an ordinary sequence of tests.