Main Page

Logical OR

?
If one operand is an object and one is a Boolean, the object is returned.
?
If both operands are objects, the second operand is returned.
?
If either operand is
null
,
null
is returned.
?
If either operand is
NaN
,
NaN
is returned.
?
If either operand is
undefined
, an error occurs.
Just as in Java, logical AND is a short-circuited operation, meaning that if the first operand determines
the result, the second operand is never evaluated. In the case of logical AND, if the first operand is false,
no matter what the value of the second operand, the result can’t be equal to true. Consider the following
example:
var bTrue = true;
var bResult = (bTrue && bUnknown); //error occurs here
alert(bResult); //this line never executes
This code causes an error when the logical AND is evaluated because the variable
bUnknown
is unde-
fined. The value of variable
bTrue
is
true
, so the logical AND operator continued on to evaluate vari-
able
bUnknown
. When it did, an error occurred because
bUnknown
is undefined and, therefore, cannot
be used in a logical AND operation. If this example is changed so that
a
is set to
false
, the error won’t
occur:
var bFalse = false;
var bResult = (bFalse && bUnknown);
alert(bResult); //outputs “false”
In this code, the script writes out the string
“false”
, the value returned by the logical AND operator.
Even though the variable
bUnknown
is undefined, it never gets evaluated because the first operand is
false
. You must always keep in mind short-circuiting when using logical AND.
Logical OR
The logical OR operator in ECMAScript is the same as in Java, using the double pipe (
||
):
var bTrue = true;
var bFalse = false;
var bResult = bTrue || bFalse;
Logical OR behaves as described in the following truth table:
Operand 1
Operand 2
Result
true
true
true
true
false
true
false
true
true
false
false
false
45
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 45


JavaScript EditorFree JavaScript Editor     Ajax Editor


©