HTML / JavaScript Reference

Ternary Operator

Overview

A unary operator works on one value (called an operand). An example is ++, which increments a variable by one. A binary operator works on two operands. An example is +, which adds one value to another. Therefore, a ternary operator works on three operands. The ternary operator being discussed here is the conditional operator. It looks like ?:, and an example is below.

Basic Rules

The conditional operator can be thought of as a shortcut to an if-else statement. The first part of the example is the variable d. This variable can equal one of two values as a result of the conditional operator. The first operand of the conditional operator is the conditional statement (toMeters). This has to evaluate to either true or false. The next operand is the result if the condition is true: (d*1609). The last operand is the result if the condition is false: (d/1609). The syntax for the ternary operator includes the question mark ? after the conditional statement, and the colon : between the two possible results. The variable d will therefore be equal to (d*1609) if (toMeters) is true. Note. The parenthesis around each operand is not necessary. It just helps clarify the order of operations to the person reading it.

Basic Rules - example source (excerpt from Pace Calculator Source)

d = (toMeters) ? (d*1609) : (d/1609);

About this page: