The Logical Operators
Most of the examples so far in the book show a conditional expression that consists usually of one operator and two operands, such as the following:
if (sValue == 'test')
However, many times a conditional expression is dependent on several different conditions being met, each represented by an expression and combined through the use of one of JavaScript’s logical operators.
There are three logical operators—two binary and one unary. The
first is the logical AND, represented by two ampersand characters,
&&. When used in a conditional statement, the AND operator
requires that expressions on both sides of the operator evaluate to
true for the entire expression to
evaluate to true:
var nValue = 10; if ((nValue > 10) && (nValue <=100)) // true if nValue is greater than 10 and nValue is less than or equal to 100
The result of using this expression joined by the AND operator is
false because the variable, nValue, is equal to 10, which means the first
expression is false. If the first
expression evaluates to false, the
JavaScript engine won’t process the second expression because the entire
statement is going to fail regardless.
The second operator is the logical OR operator, represented by two
vertical lines, ||. When used in a conditional statement, the OR
operator requires one or the other of its expressions on either side to
be true in order for the entire
expression to evaluate to true:
var nValue = 10; if ((nValue > 10) || (nValue <= 100)) // true if nValue is either ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access