18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

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

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

Chapter 2<br />

In this example, a Boolean variable (found) keeps track of the success of a search. When the item in<br />

question is located, found is set to true, which causes !found to equal false, meaning that execution<br />

will escape the while loop.<br />

The logical NOT operator is also useful in determining the Boolean equivalent of an ECMAScript variable.<br />

In order to do this, you use two logical NOT operators in a row. The first NOT returns a Boolean<br />

value no matter what operand it is given. The second NOT negates that Boolean value and so gives the<br />

true Boolean value of a variable.<br />

var bFalse = false;<br />

var sBlue = “blue”;<br />

var iZero = 0;<br />

var iThreeFourFive = 345;<br />

var oObject = new Object;<br />

document.write(“The Boolean value of bFalse is “ + (!!bFalse));<br />

document.write(“The Boolean value of sBlue is “ + (!!sBlue));<br />

document.write(“The Boolean value of iZero is “ + (!!iZero));<br />

document.write(“The Boolean value of iThreeFourFive is “ +<br />

(!!iThreeFourFive));<br />

document.write(“The Boolean value of oObject is “ + (!!oObject));<br />

Running this example yields the following output:<br />

The Boolean value of bFalse is false<br />

The Boolean value of sBlue is true<br />

The Boolean value of iZero is false<br />

The Boolean value of iThreeFourFive is true<br />

The Boolean value of oObject is true<br />

Logical AND<br />

The logical AND operator in ECMAScript is indicated by the double ampersand (&&):<br />

var bTrue = true;<br />

var bFalse = false;<br />

var bResult = bTrue && bFalse;<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 operands, not just Boolean values. When either operand is<br />

not a primitive Boolean, logical AND does not always return a Boolean value:<br />

44

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

Saved successfully!

Ooh no, something went wrong!