Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Logical Operators - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Control Statements II

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Logical Operators - JavaScript(JS)

So far, we have studied only such simple conditions as count <= 10, total > 1000 and number != sentinelValue.

Logical Operators

 

So far, we have studied only such simple conditions as count <= 10, total > 1000 and number != sentinelValue. These conditions were expressed in terms of the relational opera-tors >, <, >= and <=, and in terms of the equality operators == and !=. Each decision tested one condition. To make a decision based on multiple conditions, we performed these tests in separate statements or in nested if or ifelse statements.

 

JavaScript provides logical operators that can be used to form more complex condi-tions by combining simple conditions. The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, also called logical negation). We consider examples of each of these operators.

 

Suppose that, at some point in a program, we wish to ensure that two conditions are both true before we choose a certain path of execution. In this case, we can use the logical && operator, as follows:

 

if   ( gender == 1 && age >= 65 ) ++seniorFemales;

 

This if statement contains two simple conditions. The condition gender == 1 might be evaluated to determine, for example, whether a person is a female. The condition age >= 65 is evaluated to determine whether a person is a senior citizen. The if statement then considers the combined condition

 

gender == 1 && age >= 65

 

This condition is true if and only if both of the simple conditions are true. Finally, if this combined condition is indeed true, the count of seniorFemales is incremented by 1. If either or both of the simple conditions are false, the program skips the incrementing and proceeds to the statement following the if statement. The preceding combined condition can be made more readable by adding redundant parentheses:

 

( gender == 1 ) && ( age >= 65 )

 

The table in Fig. 8.15 summarizes the && operator. The table shows all four possible combinations of false and true values for expression1 and expression2. Such tables are often called truth tables. JavaScript evaluates to false or true all expressions that include relational operators, equality operators and/or logical operators.

 

Now let us consider the || (logical OR) operator. Suppose we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. In this case, we use the || operator, as in the following program segment:

 

if      ( semesterAverage >= 90 || finalExam >= 90 ) document.writeln( "Student grade is A" );

 

This statement also contains two simple conditions. The condition semesterAverage >= 90 is evaluated to determine whether the student deserves an “A” in the course because of a solid performance throughout the semester. The condition finalExam >= 90 is evaluated to determine whether the student deserves an “A” in the course because of an outstanding performance on the final exam. The if statement then considers the combined condition

 

semesterAverage >= 90 || finalExam >= 90

 

and awards the student an “A” if either or both of the simple conditions are true. Note that the message "Student grade is A" is not printed only when both of the simple con-ditions are false. Figure 8.16 is a truth table for the logical OR operator (||).

 

The && operator has a higher precedence than the || operator. Both operators asso-ciate from left to right. An expression containing && or || operators is evaluated only until truth or falsity is known. Thus, evaluation of the expression

 

gender == 1 && age >= 65


stops immediately if gender is not equal to 1 (i.e., the entire expression is false) and con-tinues if gender is equal to 1 (i.e., the entire expression could still be true if the condition age >= 65 is true). Similarly, the || operator immediately returns true if the first operand is true. This performance feature for evaluation of logical AND and logical OR expres-sions is called short-circuit evaluation.

 

JavaScript provides the ! (logical negation) operator to enable a programmer to “reverse” the meaning of a condition (i.e., a true value becomes false, and a false value becomes true). Unlike the logical operators && and ||, which combine two conditions (i.e., they are binary operators), the logical negation operator has only a single condition as an operand (i.e., it is a unary operator). The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical nega-tion operator) is false, as in the following program segment:

 

if      ( ! ( grade == sentinelValue ) ) document.writeln( "The next grade is " + grade );

 

The parentheses around the condition grade == sentinelValue are needed, because the logical negation operator has a higher precedence than the equality operator. Figure 8.17 is a truth table for the logical negation operator.

 

In most cases, the programmer can avoid using logical negation by expressing the con-dition differently with an appropriate relational or equality operator. For example, the pre-ceding statement may also be written as follows:

 

if ( grade != sentinelValue )

 

document.writeln( "The next grade is " + grade );

 

The script in Fig. 8.18 demonstrates all the logical operators by producing their truth tables. The script produces an XHTML table containing the results.


        <?xml version = "1.0" encoding = "utf-8"?>

 

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

        <!-- Fig. 8.18: LogicalOperators.html -->

 

        <!-- Demonstrating logical operators. -->

 

        <html xmlns = "http://www.w3.org/1999/xhtml">

 

        <head>

 

<title>Demonstrating the Logical Operators</title>

<style type = "text/css">

table    { width: 100% }

        td.left { width: 25% }

 

        </style>

 

        <script type = "text/javascript">

        <!--

 

        document.writeln(

        "<table border = \"1\"" );

 

document.writeln(

"<caption>Demonstrating Logical " +

"Operators</caption>" );                               

document.writeln(                                         

"<tr><td class = \"left\">Logical AND (&&)</td>" +

"<td>false && false: " + ( false && false ) +             

"<br />false && true: " + (      false && true ) +                    

"<br />true &&           false: " + (        true && false ) +                    

"<br />true &&           true: " + ( true && true ) +

        "</td></tr>" );

 

document.writeln(

"<tr><td class  = \"left\">Logical OR (||)</td>" +

"<td>false || false: " + ( false || false ) +                 

"<br />false || true: " + ( false || true ) +                 

"<br     />true ||         false: " + ( true || false ) +                

"<br     />true ||         true: " + ( true || true ) +

        "</td></tr>" );

 

        document.writeln(

"<tr><td class  =          \"left\">Logical NOT (!)</td>" +

"<td>!false: "   +          ( !false ) +

        "<br />!true: " + ( !true ) + "</td></tr>" );

 

        document.writeln( "</table>" );

        // -->

 

        </script>

 

        </head><body></body>

 

</html>


Fig. 8.18 | Demonstrating logical operators.

In the output of Fig. 8.18, the strings "false" and "true" indicate false and true for the operands in each condition. The result of the condition is shown as true or false. Note that when you use the concatenation operator with a boolean value and a string, JavaScript automatically converts the boolean value to string “false" or "true". Lines 16–39 build an XHTML table containing the results.

 

An interesting feature of JavaScript is that most nonboolean values can be converted to a boolean true or false value. Nonzero numeric values are considered to be true. The numeric value zero is considered to be false. Any string that contains characters is con-sidered to be true. The empty string (i.e., the string containing no characters) is consid-ered to be false. The value null and variables that have been declared but not initialized are considered to be false. All objects (e.g., the browser’s document and window objects and JavaScript’s Math object) are considered to be true.

 

Figure 8.19 shows the precedence and associativity of the JavaScript operators intro-duced up to this point. The operators are shown top to bottom in decreasing order of precedence.



Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.