The JavaScript Conditional Operator
This operator can be used to write compact code forks in JavaScript. It takes the form
(condition)?trueStatement:falseStatementwhere
- trueStatement is executed if condition is true and
- falseStatement is executed if condition is false.
The conditional operator is often considered dangerous. In our view - there are no dangerous operators, only dangerous programmers. Using this operator can result in compact code that is easy to read and to maintain. Browsers can often fail to figure out the logic of a carelessly written JavaScript conditional statement. However, this is easily avoided through a judicious use of parentheses. Study the examples below for safe and correct use of this operator.
- Calculated Assignment
oddOrEven = (Value % 2 == 0)?'even':'odd';
Is Value even? - Function Return
return (Gender == 'M')?'Mr':'Ms'
Tests the variable Gender and returns Mr or Ms. - Function Return With Nested Conditional
return (Value < 0)?-1:((Value == 0)?0:1)
Returns -1, 0 or 1 depending on whether Value is negative, zero or positive. Note the use of parentheses.
