18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ECMAScript Basics<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

If one operand is an object and one is a Boolean, the object is returned.<br />

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

If either operand is null, null is returned.<br />

If either operand is NaN, NaN is returned.<br />

If either operand is undefined, an error occurs.<br />

Just as in Java, logical AND is a short-circuited operation, meaning that if the first operand determines<br />

the result, the second operand is never evaluated. In the case of logical AND, if the first operand is false,<br />

no matter what the value of the second operand, the result can’t be equal to true. Consider the following<br />

example:<br />

var bTrue = true;<br />

var bResult = (bTrue && bUnknown); //error occurs here<br />

alert(bResult);<br />

//this line never executes<br />

This code causes an error when the logical AND is evaluated because the variable bUnknown is undefined.<br />

The value of variable bTrue is true, so the logical AND operator continued on to evaluate variable<br />

bUnknown. When it did, an error occurred because bUnknown is undefined and, therefore, cannot<br />

be used in a logical AND operation. If this example is changed so that a is set to false, the error won’t<br />

occur:<br />

var bFalse = false;<br />

var bResult = (bFalse && bUnknown);<br />

alert(bResult); //outputs “false”<br />

In this code, the script writes out the string “false”, the value returned by the logical AND operator.<br />

Even though the variable bUnknown is undefined, it never gets evaluated because the first operand is<br />

false. You must always keep in mind short-circuiting when using logical AND.<br />

Logical OR<br />

The logical OR operator in ECMAScript is the same as in Java, using the double pipe (||):<br />

var bTrue = true;<br />

var bFalse = false;<br />

var bResult = bTrue || bFalse;<br />

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

Operand 1 Operand 2 Result<br />

true true true<br />

true false true<br />

false true true<br />

false false false<br />

45

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

Saved successfully!

Ooh no, something went wrong!