﻿ Conditional operator ﻿

Main Page

# Conditional operator

operator to compare the string and the number without conversion, and of course, a string isn’t equal to
a number, so this outputs
“false”
.
The not identically equal operator is represented by an exclamation point followed by two equal signs
(
!==
) and returns
true
only if the operands are not equal without conversion. For example:
var sNum = “55”;
var iNum = 55;
Here, the first alert uses the not equal operator, which converts the string
“55”
to the number
55
, mak-
ing it equal to the second operand, also the number
55
. Therefore, this evaluates to
false
because the
two are considered equal. The second alert uses the not identically equal operator. It helps to think of
this operation as saying, “is
sNum
different from
iNum
?” The answer to this is yes (
true
), because
sNum
is a string and
iNum
is a number, so they are very different.
Conditional operator
The conditional operator is one of the most versatile in ECMAScript, and it takes on the same form as
in Java:
variable
=
boolean_expression
?
true_value
:
false_value
;
This basically allows a conditional assignment to a variable depending on the evaluation of the
boolean_expression
. If it’s true, then
true_value
is assigned to the variable; if it’s false, then
false_value
is assigned to the variable. For instance:
var iMax = (iNum1 > iNum2) ? iNum1 : iNum2;
In this example,
iMax
is to be assigned the number with the highest value. The expression states that if
iNum1
is greater than
iNum2
,
iNum1
is assigned to
iMax
. If, however, the expression is false (meaning
that
iNum2
is less than or equal to
iNum1
),
iNum2
is assigned to
iMax
.
Assignment operators
Simple assignment is done with the equals sign (
=
) and simply assigns the value on the right to the vari-
able on the left. For example:
var iNum = 10;
Compound assignment is done with one of the multiplicative, additive, or bitwise shift operators fol-
lowed by an equals sign (=). These assignments are designed as shorthand for such common situations as:
var iNum = 10;
iNum = iNum + 10;
The second line of code can be replaced with a compound assignment:
52
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 52

Free JavaScript Editor     Ajax Editor