Example: Below is an example of the Ternary Operator.
Characteristics of Ternary Operator:
- The expression consists of three operands: the condition, value if true and value if false.
- The evaluation of the condition should result in either true/false or a boolean value.
- The true value lies between “?” & “:” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false.
condition ? value if true : value if false
- condition: Expression to be evaluated which returns a boolean value.
- value if true: Value to be executed if condition results in true state.
- value if false: Value to be executed if condition results in false state.
Input: let result = (10 > 0) ? true : false; Output: true Input: let message = (20 > 15) ? "Yes" : "No"; Output: Yes
The following examples will illustrate conditional operator more extensively. Example 1:
Example 2: An example of multiple conditional operators.