Using Shorthand Conditional Expressions
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.
These shorthand expressions can be used anywhere JavaScript expects a value. They provide an easy way to make simple decisions about values. As an example, here's an easy way to display a grammatically correct message about a variable:
document.write("Found " + counter + ((counter == 1) ? " word." : " words."));
This will print the message Found 1 word if the counter variable has a value of 1, and Found 2 words if its value is 2 or greater. This is one of the most common uses for a conditional expression.
|