Section G. Working with booleans


G. Working with booleans

Boolean values are simple to work with, but by themselves they're limited. Although you'll occasionally use a variable with a boolean value, the most important use of the boolean data type is with the if statement.

Variables with boolean values

A boolean value is either true or false. Variables commonly get a boolean value when they answer a Yes/No question like "Is this form valid?". Take validForm from Form Validation:

[Form Validation, lines 73-75, condensed]

function validate() {     var validForm = true; 


When the validate() function starts up, it sets the validForm variable to true, because initially it assumes that the form is valid:

[Form Validation, lines 89-92, condensed]

if (OK != true) { // if the form field contains an error     // administration     validForm = false; 


When the script encounters an error in the form, validForm becomes false. At the end of the function, it's used to decide what to do next:

[Form Validation, lines 100-104, condensed]

if (!validForm) {     alert("Errors have been found"); } return validForm; 


The if statement says "if NOT validForm", or "if validForm is false". Then validForm is returned to the submit event handler. If this return value is false, the form is not submitted to the server (see 7B). This is exactly what we want: the form should be submitted only if it contains no errors and validForm is true.

Boolean operators

The line if (!validForm) brings us to our next topic: &&, ||, and ! (also called AND, OR, and NOT). These are the three main boolean operators, and you'll use them in if statements and occasionally in other circumstances.

I'll use two test boolean values to demonstrate how these operators work:

var x = true; var y = false; 


The NOT operator !

The NOT operator reverses a boolean. If the variable is true it becomes false and vice versa:

var z = !x; 


z is false, because x is true and the ! operator reverses that value.

The AND operator &&

The AND operator takes two booleans and returns true if all are true. Otherwise it returns false:

var z = x && y; 


z is false because y is false. For z to become true, both x and y have to be true.

The OR operator ||

The OR operator takes two booleans and returns false if all are false. Otherwise it returns true:

var z = x || y; 


z is true because x is true. For z to become false, both x and y have to be false.

Bitwise Operators & and |

JavaScript also contains the bitwise operators & and | (which perform bitwise AND and OR). If you don't know what bitwise AND and OR are, don't worry. You rarely need these operations in normal JavaScript.

Just make sure that you write && and || if you want to use the boolean AND and OR.


Combining boolean operators

You can combine these three operators to define quite complex boolean expressions.

Let's add a third example value:

var x = true; var y = false; var z = false; 


Now let's combine these variables and the three boolean operators:

var a = x && (y || !z); 


What's a's value? Start by swapping in the values of x, y, and z:

var a = true && (false || !false); 


Now resolve the NOT:

var a = true && (false || true); 


Then resolve the part between parentheses (which, as usual, comes first). Since false || true is true, we get:

var a = true && true; 


Now you know that a is true.

Boolean Generator

If you're not used to working with boolean logic, it's worth practicing. I have created a boolean generator that allows you to create and evaluate boolean expressions. You can find it at http://www.quirksmode.org/js/boolean.html.


Testing if an object exists

The if() statement hinges on boolean values. The expression between the parentheses is evaluated as a boolean, and data-type conversion makes sure that all parts of such an expression are interpreted as booleans.

Remember the rules of converting a value to a boolean?

  • The special values undefined and null become false.

  • The numbers 0 and NaN become false.

  • An empty string becomes false.

  • All other values become true.

The conversion of an object to a boolean forms the core of object detection that we discussed in 3C. Let's repeat the example:

[Edit Style Sheet, lines 5-6]

function initStyleChange() {    if (!document.styleSheets) return; 


document.styleSheets is supposed to be an object, but the browser might not support it. In any case, the if() statement forces data-type conversion from object to boolean:

  • If the browser supports document.styleSheets, the object exists and is converted to boolean true.

  • If the browser does not support document.styleSheets, the object does not exist. As we saw in 5B, an object that does not exist has the value null, which in turn converts to boolean false.

The NOT operator reverses this value. Therefore, the browser ends the function (return) if the if() statement returns true, i.e., if document.styleSheets evaluates to false: if the browser does not support the object.

A more complicated example is my favorite line of object detection, which checks if the W3C DOM is supported:

var W3CDOM = document.getElementsByTagName && document.createElement; 


It checks if the browser supports getElementsByTagName and createElement. The principle is the same: if these methods (with data-type object) exist, they evaluate to true; if they don't exist, they are null and evaluate to false. If a browser supports both of them (&&), it supports the W3C DOM.

Advanced uses of boolean operators

The value returned by the && and || operators is unusual. To show why, let's look at a case that involves strings and numbers:

var x = '2'; var y = '3'; var z = x * y; 


As we saw earlier, the strings x and y are interpreted as numbers, the multiplication is executed, and the value the operation evaluates to (which is a number) is stored in z. Therefore, z now becomes a number, though x and y remain strings.

Now let's look at our last object-detection line:

var W3CDOM = document.getElementsByTagName && document.createElement; 


Both objects are interpreted as booleans in order to perform the operation &&. Now you'd expect W3CDOM to become a boolean, too, just as z became a number in the previous example.

But that doesn't happen. The boolean operators && and || don't return true or false, but rather the value of the last expression they evaluated. This is very much an exception to the general rule:

var W3CDOM = document.getElementsByTagName && document.createElement; alert(W3CDOM): 


The alert now displays:

function createElement() { [native code] } 


The document.createElement expression was evaluated last; hence W3CDOM now contains its value (which is a native browser function).

However, the last expression that was evaluated doesn't have to be the last expression in the statement. In order to discuss this potentially confusing feature, we have to take a closer look at how boolean operators work. Take this example:

var z = x || y; 


As we saw, the expression x || y becomes true if either x or y (or both) are true. The point is that if x is true, the expression automatically becomes true, too. Therefore JavaScript doesn't have to evaluate y; its value doesn't matter any more.

In other words, if x evaluates to true, JavaScript doesn't evaluate y because it isn't necessary to do so. The || operator returns the value of the expression that was evaluated last, and therefore z now contains x's value.

The reverse happens here:

var z = x && y; 


As we saw, x && y becomes true if both x and y are true. Therefore, if x is false, the expression automatically becomes false, too. JavaScript doesn't have to evaluate y any more.

Using the && and || oddities

We can use these facts in interesting ways. As we'll see in 7F, most browsers store the event target in evt.target, but Explorer uses evt.srcElement instead. Therefore, any function that wants to use this target first has to find out where the browser stores it. I use this line:

[Usable Forms, line 71]

var evtTarget = evt.target || evt.srcElement; 


What happens? JavaScript encounters a || operator and starts evaluating the first expression (evt.target). If the browser is W3C DOM-compliant, evt.target exists, i.e., it is not undefined, and JavaScript has found an expression that evaluates to true. It doesn't have to go on to the next expression, so it breaks off the || operation.

Nonetheless, || doesn't return true, but the value of the expression that was last evaluated, i.e., evt.target's value, which is the target of the event. That's exactly the bit of data we need.

If the browser is Explorer, evt.target is undefined, which converts to boolean false. Therefore JavaScript proceeds to the second expression, and since evt.srcElement exists, it evaluates as true. Again, || doesn't return true, but the value of the expression that was last evaluated (evt.srcElement), which is again the target of the event.

In other words, evtTarget now contains the target of the event, whether that information is found in evt.target or evt.srcElement. You'll often use this trick when there are several possible locations for one bit of data.

Using && as On-the-Spot Object Detection

It's possible to use the && operator in a similar way, although I never do so:

var x = document.createElement && document.createElement('div'); 


This statement first evaluates document.createElement. If it doesn't exist, it returns the value null, which converts to boolean false. Now it stops, since it knows enough (&& can never return true if one of its operands is false). That's a good thing, since the second expression would give an error message if a browser that doesn't support createElement() tried to execute it.

If createElement does exist, it evaluates document.createElement('div') (in other words, it creates a div) and returns its value (the div) to x.

This is a sort of on-the-spot object detection: "I want to use createElement. Does it exist?" The problem is that if you use this kind of object detection, you have to repeat it on every single line that uses a W3C DOM method. The object detection described in 3C is easier to write and maintain.




ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net