The Power of Javascript: Operators concluded - Logical Operators Example
(Page 2 of 5 )
Here's an example that explains the logical operators for now (we will use it all the time with if/else statements and loop statements, but for now a simple example is in order). Copy the following code (or write it) to an HTML document and save it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
<script language="JavaScript" type="text/javascript">
var x = 5;
var y = 8;
var z = 13;
var result = (y > x && z == (x + y));
alert("y > x && z == (x + y) is " + result);
var result = (y < x || z == (x + y));
alert("y < x || z == (x + y) is " + result);
var result = 0;
alert(!result);
</script>
</head>
<body>
</body>
</html>
Load the document with your browser and you will get the following three message boxes, respectively.



We have declared x and assigned it the value 5, then y was assigned the value 8, then z received the value 13. The statement var result = (y > x && z == (x + y)); declared and assigned the value true to the variable result by evaluating the expression to the right of the assignment operator. In this expression we have used the comparison operators greater than and equal to to state the relationship between x, y and z. We also combined the logical AND operator (&&) to form a somewhat more complex expression which evaluates to true only if the first operand and the second operand (of the AND Operator) evaluate to true.
In this example, y is greater than x, so it produces true, and z equals x + y, so it also produces true. Therefore the whole expression evaluates to true. This boolean value is assigned to the variable result and displayed in the message box using the statement alert ("y > x && z == (x + y) is " + result); which concatenates a string value with the value of the variable result.
There's nothing special about the next statement that uses the logical OR || operator. It just evaluates its left operand, which produces the value false, then it evaluates its right operand which produces the value true. Because the operator || produces the value true if any of its operands evaluate to true, we see true displayed in the message box. The statement var result = 0; assigns the numerical value 0 to the variable result (which means false), then alert (!result); displays a message box that inverts the value of the result variable. The value was false so !false means true. I think that it should be easy by now.
Next: The Operator typeof >>
More JavaScript Articles
More By Michael Youssef