HTML and CSS Reference
In-Depth Information
The logical operators allow you combine the relational operators into more powerful
expressions for testing conditions and are most often used in if statements. They evalu-
ate their operands from left to right, testing the Boolean value of each operand in turn:
Does the operand evaluate to true or false? In the expression if ( x > 5 && x < 10 ), the
&& is a logical operator. The expression simplified means, “if x is greater than 5 and x
is also less than 10, then do something”; in the case of the logical AND ( && ), if the first
expression returns true and the second expression also returns true , then the whole
expression is true. If instead of && we used || , the operator means OR and only one of
the expressions must be true.
Sometimes the result of a test is not Boolean. When logical operators have numeric
operands, such as 5 && 6 , the result of the entire expression is evaluated from left to
right, and the value returned is that of the last expression. A numeric operand is true if
it evaluates to any number that is not zero. 5, -2, and 74 are all true. 0 is false. For exam-
ple, when using the && (AND) operator, both operands must be true for the whole
expression to be true. The value returned from an expression such as 5 && 6 is 6 , the
last value evaluated by the operator. 5 is not zero (true) and 6 is not zero (true), there-
fore, the expression is true. If the expression contained a 0 as in 5 && 0, 0 && 0 and
0 && 5 all yield 0 , which is false. Because the && operator wants all of its operands to
be nonzero values, as soon as the value 0 is encountered in the expression, 0 is the result
of the whole expression. See Table 5.11.
The three logical operators are the logical AND, logical OR, and logical NOT. The
symbol for AND is && , the symbol for OR is || , and the symbol for NOT is ! .
Table 5.11 Logical Operators and Their Functions
Operator/Operands
Function
num1 && num2
True, if num1 and num2 are both true. Returns num1 if num1
is false; otherwise returns num2 . If operands are Boolean
values, returns true if both operands are true; otherwise
returns false .
num1 || num2
True, if num1 is true or if num2 is true.
! num1
Not num1; true if num1 is false; false if num1 is true.
The && Operator (Logical AND). We l know the m aning of the En sh -
ment, “If you have the money and I have the time....” Whatever is supposed to happen
is based on two conditions, and both conditions must be met. You must have the money
and I must have the time. JavaScript uses the symbol && to represent the word AND.
This operator is called the logical AND operator. If the expression on the left side of the
&& evaluates to zero, null, or the empty string “”, the expression is false. If the expres-
sion on the left side of the operator evaluates to true (nonzero), then the right side is
evaluated, and if that expression is also true, then the whole expression is true. If the left

Search WWH ::

Custom Search