November 10, 1999 - The Conditional Operator | WebReference

November 10, 1999 - The Conditional Operator

Yehuda Shiran November 10, 1999
The Conditional Operator
Tips: November 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

The conditional operator is unique because it is trinary (three operands) and because it returns values of all types. It can return a numeric value, a string, a Boolean value, and so on. The first operand is the condition. The condition must be an expression that evaluates to a Boolean value, either true or false. The second operator holds the value that the operator should return if the condition is true. The third operand is the value that the expression evaluates to if the condition is false. The conditional operator is often used with an assignment operator. For example:

var level = (points > 500) ? "Second Level" : "First Level";

The variable level is assigned either "First Level" or "Second Level", depending on the value of the Boolean expression points > 500. If the value of points is greater than 500, the conditional expression evaluates to the string "Second Level", which in turn is assigned to the variable level. If the value of points does not exceed 500, the string "First Level" is assigned to the variable. The first operand (the condition) must be Boolean (a single Boolean value or an expression that evaluates to a single Boolean value). The other operands can be of any type.