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.

Chapter 2<br />

Just like logical AND, if either operand is not a Boolean, logical OR will not always return a Boolean<br />

value:<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 first operand is returned.<br />

If both operands are null, null is returned.<br />

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

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

Also like the logical AND operator, the logical OR operator is short-circuited. In this case, if the first<br />

operand evaluates to true, the second operand is not evaluated. <strong>For</strong> example:<br />

var bTrue = true;<br />

var bResult = (bTrue || bUnknown);<br />

alert(bResult);<br />

//outputs “true”<br />

As with the previous example, the variable c is undefined. However, because the variable bTrue is set<br />

to true, variable bUnknown is never evaluated and thus the output is “true”. If the value of bTrue is<br />

changed to false, an error occurs:<br />

var bFalse = false;<br />

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

alert(bResult);<br />

//this line never executes<br />

Multiplicative operators<br />

This next section deals with the three multiplicative operators: multiple, divide, and modulus. These<br />

operators work in a manner similar to their counterparts in languages such as Java, C, and Perl, but they<br />

also include some automatic type conversions you need to be aware of.<br />

Multiply<br />

The multiply operator is represented by an asterisk (*) and is used, as one might suspect, to multiply two<br />

numbers. The syntax is the same as in C:<br />

var iResult = 34 * 56;<br />

However, the multiply operator also has some unique behaviors when dealing with special values:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

If the operands are numbers, regular arithmetic multiply is performed, meaning that two positives<br />

or two negatives equal a positive, whereas operands with different signs yield a negative.<br />

If the result is too high or too low, the result is either Infinity or –Infinity.<br />

If either operand is NaN, the result is NaN.<br />

If Infinity is multiplied by 0, the result is NaN.<br />

If Infinity is multiplied by any number other than 0, the result is either Infinity or<br />

–Infinity, depending on the sign of the second operand.<br />

If Infinity is multiplied by Infinity, the result is Infinity.<br />

46

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

Saved successfully!

Ooh no, something went wrong!