Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In addition to the if statement, JavaScript provides a shorthand type of conditional expression that you can use to make quick decisions. This uses a peculiar syntax that is also found in other languages, such as C. A conditional expression looks like this:
variable = (condition) ? (true action) : (false action);
This assigns one of two values to the variable: one if the condition is true, and another if it is false. Here is an example of a conditional expression:
value = (a == 1) ? 1 : 0;
This statement might look confusing, but it is equivalent to the following if statement:
if (a == 1) {
value = 1;
} else {
value = 0;
}
In other words, the value after the question mark (?) will be used if the condition is true, and the value after the colon (:) will be used if the condition is false. The colon represents the else portion of this statement and, like the else portion of the if statement, is optional.