Friday 24 August 2018

JavaScript: Logical operators

JavaScript provides three logical operators, These are &&(AND), || (OR), and !(NOT)

Logical AND is also called Conditional AND

Logical OR is also called Conditional OR

Logical AND, OR are called Short circuit operators, will see why these are called short circuit soon.

Logical AND Operator
Operand1
Operand2
Evaluates To
true
true
true
true
false
false
false
true
false
false
false
false

Why Logical AND is called short circuit operator?
Since if the first statement in the expression evaluates to false, then Javascript won't evaluates the entire expression.

Logical OR Operator
Operand1
Operand2
Evaluates To
true
true
true
true
false
true
false
true
true
false
false
false

As shown in the above table, || operator returns true if any of the operand evaluates to true, otherwise returns false.

Why Logical OR is called short circuit operator?
Since if the first statement evaluates to true, then JavaScript won't evaluates the entire expression.

Logical (!)NOT operator
Operand
Evaluates To
false
true
true
false

If the operand is false, ! Operator evaluates it to true
If the operand is true, ! Operator evaluates it to false.

logical.html

<!DOCTYPE html>

<html>

<head>
    <title>Logical Operators</title>

    <style>
        p {
            font-size: 2em;
            color: seagreen;
        }
    </style>
</head>

<body>
    <p>
        <script type="text/javascript">
            var a = true;
            var b = true;
            var c = false;
            var d = false;

            document.write("a = " + a + "<br />");
            document.write("b = " + b + "<br />");
            document.write("c = " + c + "<br />");
            document.write("d = " + d + "<br />");

            document.write("a&&b = " + (a && b) + "<br />");
            document.write("a&&c = " + (a && c) + "<br />");
            document.write("c&&d = " + (c && d) + "<br /><br />");

            document.write("a||b = " + (a || b) + "<br />");
            document.write("a||c = " + (a || c) + "<br />");
            document.write("c||d = " + (c || d) + "<br />");
        </script>
    </p>
</body>

</html>



Previous                                                 Next                                                 Home

No comments:

Post a Comment