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 ...
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.