Conditional ternary operators
We did not actually discuss this very important operator in our section on operators in Chapter 2, JavaScript Essentials. This is because it helps to understand the if else statement first. Remember that we had a unary operator that was called a unary operator because it only had one operand? This is why our ternary operator has its name; it has three operands. Here is its template:
operand1 ? operand2 : operand3;
operand1
is the expression that is to be evaluated. If the value of the expression is true
, operand2
gets executed. If the value of the expression is false
, operand3
gets executed. You can read the question mark as "then" and the colon as "else" here:
expression ? statement for true : statement associated with false;
The template for saying it in your head should be:
if *operand1*, then *operand2*, else *operand3*
Let's have a look at a few examples:
let access = age < 18 ? "denied...