HTML and CSS Reference
In-Depth Information
Using a Conditional Operator
The code needs to run different operations based on the hours value. You can specify
these options through the use of a conditional operator. A conditional operator is an
operator that tests whether a specified condition is true. If the condition is true, one value
is returned; if the condition is not true, a different value is returned. The syntax of a con-
ditional operator is
( condition ) ? trueValue : falseValue
where condition is an expression that is either true or false, trueValue is the value
returned if the condition is true, and falseValue is the value returned if the condi-
tion is false. You can use a conditional operator to assign a value to a variable using the
statement
variable = ( condition ) ? trueValue : falseValue ;
where variable is the variable to which the resulting value is assigned.
Using Comparison Operators
To create expressions that have true or false values, you use comparison operators.
A comparison operator is an operator that compares the value of one expression to
another. One commonly used comparison operator is the less than operator ( < ), which
is used to determine whether one value is less than another. The following expression
demonstrates the use of the less than ( < ) comparison operator:
x < 100
If the value of the x variable is less than 100, then this expression is true; but if x is
greater than or equal to 100, the expression is false. Figure 11-29 lists the comparison
operators supported by JavaScript.
Figure 11-29
comparison operators
Operator
Definition
Expression
Description
==
equal to
x == y
Returns true if x equals y
!=
not equal to
x != y
Returns true if x does not equal y
>
greater than
x > y
Returns true if x is greater than y
<
less than
x < y
Returns true if x is less than y
>=
greater than or
equal to
x >= y
Returns true if x is greater than or equal to y
<=
less than or
equal to
x <= y
Returns true if x is less than or equal to y
When you want to test whether two values are equal, you use a double equal
sign ( == ) rather than a single equal sign. Thus, to test whether x is equal to 100, you use
the following expression:
The symbols in the ==
comparison operator must
be entered without a
space between the two =
symbols.
x == 100
If x is equal to 100, then this expression returns the Boolean value true ; otherwise, it
returns the Boolean value false . Using the single equal sign ( = ) is a common program-
ming mistake; but remember that the equal sign is an assignment operator and is reserved
for setting one value equal to another, not for testing whether two values are equal.
 
Search WWH ::




Custom Search