04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: Language Basics<br />

The following example illustrates this behavior:<br />

alert(!false);<br />

alert(!”blue”);<br />

alert(!0);<br />

alert(!NaN);<br />

alert(!””);<br />

alert(!12345);<br />

//true<br />

//false<br />

//true<br />

//true<br />

//true<br />

//false<br />

The logical NOT operator can also be used to convert a value into its Boolean equivalent. By using two<br />

NOT operators in a row, you can effectively simulate the behavior of the Boolean() casting function.<br />

The first NOT returns a Boolean value no matter what operand it is given. The second NOT negates that<br />

Boolean value and so gives the true Boolean value of a variable. The end result is the same as using the<br />

Boolean() function on a value, as shown here:<br />

alert(!!”blue”);<br />

alert(!!0);<br />

alert(!!NaN);<br />

alert(!!””);<br />

alert(!!12345);<br />

//true<br />

//false<br />

//false<br />

//false<br />

//true<br />

Logical AND<br />

The logical AND operator is represented by the double ampersand ( & & ) and is applied to two values,<br />

such as in this example:<br />

var result = true & & false;<br />

Logical AND behaves as described in the following truth table:<br />

Operand 1 Operand 2 Result<br />

True true true<br />

True false false<br />

False true false<br />

False false false<br />

Logical AND can be used with any type of operand, not just Boolean values. When either operand is not<br />

a primitive Boolean, logical AND does not always return a Boolean value; instead, it does one of the<br />

following:<br />

❑<br />

❑<br />

❑<br />

If the first operand is an object, then the second operand is always returned.<br />

If the second operand is an object, then the object is returned only if the first operand evaluates<br />

to true .<br />

If both operands are objects, then the second operand is returned.<br />

52

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!